Victor :
table_a
user_id score
1 10
2 10
3 10
5 43
6 43
9 20
10 42
table_b
user_id flag
1 0
2 0
3 0
4 1
5 1
6 0
7 1
In the above case, how can I populate the table_b.flag
to 1
if user_id
from table_a
has a (score > 40
)?
Nick :
You can use a multi-table UPDATE
to get the results you want:
UPDATE table_b b
JOIN table_a a ON a.user_id = b.user_id AND a.score > 40
SET b.flag = 1
The JOIN
condition means that only rows in table_b
where the corresponding user_id
in table_a
has a score > 40
will have their flag set to 1
. If you want to also set flags to 0
if the corresponding score <= 40
, you can use the condition as the value to SET
(since MySQL treats booleans as 1
or 0
in a numeric context):
UPDATE table_b b
JOIN table_a a ON a.user_id = b.user_id
SET b.flag = a.score > 40
For your sample data, the result in table_b
is the same:
user_id flag
1 0
2 0
3 0
4 1
5 1
6 1
7 1
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=386128&siteId=1