MYSQL - 如何更新由选择语句分组产生的所有项目的字段

MYSQL - how to update a field for all items resulting from group by select statement(MYSQL - 如何更新由选择语句分组产生的所有项目的字段)
本文介绍了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);

这篇关于MYSQL - 如何更新由选择语句分组产生的所有项目的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)