简体   繁体   English

是否有更快的替代方法可以插入 mysql 中的 X(从 Z 处选择 Y)?

[英]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_idtable_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 在数字上下文中将布尔值视为10 ):

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

Demo on dbfiddle dbfiddle 上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM