MYSQL - 如何更新select by statement语句产生的所有项目的字段

时间:2010-02-23 12:37:29

标签: mysql sql-update

我有这样的选择:

SELECT field1, field2, field3 
FROM table WHERE field1= 5  AND field_flag =1 
GROUP BY field1, field2, field3 limit 1000;

我想更新结果行的field_flag。我怎么能在MySQL中做到这一点?

2 个答案:

答案 0 :(得分:1)

你的意思是你想更新table1,field2和field3在select语句返回的集合中的表吗?

例如。

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行。

也可以使用临时表:

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,还可以添加索引以加快更新速度:

create index on temptab (field1, field2, field3);

答案 1 :(得分:-1)

怎么样:

UPDATE table SET field_flag = <newvalue>
WHERE  idfield IN (
    SELECT idfield
    FROM table
    WHERE <conditions>
)