[英]Is there a faster alternative to insert into X (select Y from where Z) in mysql?
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
)?在上述情况下,如果
table_a
中的user_id
具有 ( score > 40
),我如何将table_b.flag
填充为1
?
You can use a multi-table UPDATE
to get the results you want:您可以使用多表
UPDATE
来获得您想要的结果:
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
.该
JOIN
条件意味着在只行table_b
,其中相应的user_id
在table_a
具有score > 40
将具有其标志设置为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):如果您还想在相应的
score <= 40
将标志设置为0
则可以使用条件作为SET
的值(因为 MySQL 在数字上下文中将布尔值视为1
或0
):
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:对于您的示例数据,
table_b
的结果是相同的:
user_id flag
1 0
2 0
3 0
4 1
5 1
6 1
7 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.