MYSQL - 如何更新由选择语句分组产生的所有项目的字段
我有一个这样的选择:
SELECT field1, field2, field3
FROM table WHERE field1= 5 AND field_flag =1
GROUP BY field1, field2, field3 limit 1000;
我想更新结果行的 field_flag.我如何在 MySQL 中做到这一点?
I want to update field_flag for the resulting rows. How can I do that in MySQL?
推荐答案
您的意思是要更新 select 语句返回的集合中的 field1、field2 和 field3 的表吗?
Do you mean that you want to update table where field1, field2, and field3 are in the set returned by your select statement ?
例如.
update table,
( select field1, field2, field3
FROM table WHERE field1= 5 AND field_flag =1
GROUP BY field1, field2, field3 limit 1000 ) temp
set table.field_flag = 99
where table.field1=temp.field1 and table.field2=temp.field2 and table.field3 = temp.field3
请注意,更新可能会更新超过 1000 行.
Note that the update might update many more than 1000 rows.
也可以使用临时表:
create temporary table temptab as
select field1, field2, field3
FROM table WHERE field1= 5 AND field_flag =1
GROUP BY field1, field2, field3 limit 1000
update table,
temptab temp
set table.field_flag = 99
where table.field1=temp.field1 and table.field2=temp.field2 and table.field3 = temp.field3
这样做的好处是可以稍后使用temptab,并且可以添加索引以加快更新:
This has the advantage that temptab can be used later, and also that indexes can be added to speed up the update:
create index on temptab (field1, field2, field3);
相关文章