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

发布于 2024-08-23 00:46:17 字数 215 浏览 2 评论 0原文

我有一个这样的选择:

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

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

I have a select like this:

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

I want to update field_flag for the resulting rows. How can I do that in MySQL?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北城挽邺 2024-08-30 00:46:17

您的意思是要更新表,其中 field1、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);

Do you mean that you want to update table where field1, field2, and field3 are in the set returned by your select statement ?

eg.

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

Note that the update might update many more than 1000 rows.

A temporary table could be used too:

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

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);
屋檐 2024-08-30 00:46:17

怎么样:

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

How about:

UPDATE table SET field_flag = <newvalue>
WHERE  idfield IN (
    SELECT idfield
    FROM table
    WHERE <conditions>
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文