MySQL 中的多次更新
我知道你可以一次插入多行,有没有一种方法可以在 MySQL 中一次更新多行(如在一个查询中)?
编辑: 例如,我有以下内容
Name id Col1 Col2
Row1 1 6 1
Row2 2 2 3
Row3 3 9 5
Row4 4 16 8
,我想将以下所有更新合并到一个查询中
UPDATE table SET Col1 = 1 WHERE id = 1;
UPDATE table SET Col1 = 2 WHERE id = 2;
UPDATE table SET Col2 = 3 WHERE id = 3;
UPDATE table SET Col1 = 10 WHERE id = 4;
UPDATE table SET Col2 = 12 WHERE id = 4;
I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL?
Edit:
For example I have the following
Name id Col1 Col2
Row1 1 6 1
Row2 2 2 3
Row3 3 9 5
Row4 4 16 8
I want to combine all the following Updates into one query
UPDATE table SET Col1 = 1 WHERE id = 1;
UPDATE table SET Col1 = 2 WHERE id = 2;
UPDATE table SET Col2 = 3 WHERE id = 3;
UPDATE table SET Col1 = 10 WHERE id = 4;
UPDATE table SET Col2 = 12 WHERE id = 4;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(20)
这应该可以达到您想要的效果。 只需添加更多 id 即可。 我已经测试过了。
This should achieve what you'r looking for. Just add more id's. I have tested it.
// 你只需在 php 中构建它,这样
你就可以用一个查询更新孔表
// You just building it in php like
So you can update hole table with one query
我从 @newtover 获取了答案,并使用 MySql 8 中的新 json_table 函数对其进行了扩展。这允许您创建一个存储过程来处理工作负载,而不是在代码中构建自己的 SQL 文本:
它比纯 SQL 慢几毫秒,但是我很乐意接受打击,而不是在代码中生成 sql 文本。 不确定它对于巨大的记录集(JSON 对象的最大大小为 1Gb)的性能如何,但我在一次更新 10k 行时一直使用它。
I took the answer from @newtover and extended it using the new json_table function in MySql 8. This allows you to create a stored procedure to handle the workload rather than building your own SQL text in code:
It's a few ms slower than pure SQL but I'm happy to take the hit rather than generate the sql text in code. Not sure how performant it is with huge recordsets (the JSON object has a max size of 1Gb) but I use it all the time when updating 10k rows at a time.
最简单的方法
Simplest Way
以下将更新一个表中的所有行
下一个将更新 Column2 的值大于 5 的所有行
全部都是 Unkwntech 更新多个表的示例
The following will update all rows in one table
The next one will update all rows where the value of Column2 is more than 5
There is all Unkwntech's example of updating more than one table
使用
请注意:
引用表,REPLACE 删除然后插入,所以这可能
导致错误
use
Please note:
reference the table, REPLACE deletes then inserts, so this might
cause an error
是的..可以使用 INSERT ON DUPLICATE KEY UPDATE sql 语句..
句法:
INSERT INTO 表名 (a,b,c) 值 (1,2,3),(4,5,6)
重复密钥更新 a=VALUES(a),b=VALUES(b),c=VALUES(c)
Yes ..it is possible using INSERT ON DUPLICATE KEY UPDATE sql statement..
syntax:
INSERT INTO table_name (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE a=VALUES(a),b=VALUES(b),c=VALUES(c)
您可能还对在更新上使用联接感兴趣,这也是可能的。
编辑:如果您要更新的值不是来自数据库中的其他位置,您将需要发出多个更新查询。
You may also be interested in using joins on updates, which is possible as well.
Edit: If the values you are updating aren't coming from somewhere else in the database, you'll need to issue multiple update queries.
还没有人提到对我来说更简单的方法来做到这一点 - 使用允许您执行多个单独查询的 SQL 编辑器。 此屏幕截图来自 Sequel Ace,我假设 Sequel Pro 和可能其他编辑器具有类似的功能。 (当然,这是假设您只需要将其作为一次性的事情来运行,而不是作为应用程序/网站的集成部分)。
No-one has yet mentioned what for me would be a much easier way to do this - Use a SQL editor that allows you to execute multiple individual queries. This screenshot is from Sequel Ace, I'd assume that Sequel Pro and probably other editors have similar functionality. (This of course assumes you only need to run this as a one-off thing rather than as an integrated part of your app/site).
您可以为同一个表添加别名,以提供要插入的 id(如果您正在进行逐行更新:
此外,很明显您也可以从其他表进行更新。在这种情况下,更新兼作“SELECT”语句,为您提供指定表中的数据,您在查询中明确说明了更新值,因此第二个表不受影响。
You can alias the same table to give you the id's you want to insert by (if you are doing a row-by-row update:
Additionally, It should seem obvious that you can also update from other tables as well. In this case, the update doubles as a "SELECT" statement, giving you the data from the table you are specifying. You are explicitly stating in your query the update values so, the second table is unaffected.
您可以更改一个名为“多语句”的设置,它会禁用 MySQL 的“安全机制”,以防止(多个)注入命令。 这是 MySQL“出色”实现的典型特征,它还会阻止用户进行高效查询。
这里(http://dev.mysql.com /doc/refman/5.1/en/mysql-set-server-option.html)是有关设置的 C 实现的一些信息。
如果您使用 PHP,您可以使用 mysqli 执行多语句(我认为 php 已经附带 mysqli 一段时间了)
希望有所帮助。
There is a setting you can alter called 'multi statement' that disables MySQL's 'safety mechanism' implemented to prevent (more than one) injection command. Typical to MySQL's 'brilliant' implementation, it also prevents user from doing efficient queries.
Here (http://dev.mysql.com/doc/refman/5.1/en/mysql-set-server-option.html) is some info on the C implementation of the setting.
If you're using PHP, you can use mysqli to do multi statements (I think php has shipped with mysqli for a while now)
Hope that helps.
为什么没有人提到一个查询中的多个语句?
在 php 中,您使用 mysqli 实例的
multi_query
方法。来自 PHP 手册
以下是更新 30,000 个原始数据时与其他 3 种方法的结果比较。 代码可以在此处找到,该代码基于以下答案@Dakusan
交易:5.5194580554962
插入:0.20669293403625
案例:16.474853992462
Multi: 0.0412278175354
可以看到,多语句查询比最高答案效率更高。
如果你收到这样的错误消息:
你可能需要增加mysql配置文件中的
max_allowed_packet
,在我的机器上是/etc/mysql/my.cnf
,然后重新启动mysqld 。Why does no one mention multiple statements in one query?
In php, you use
multi_query
method of mysqli instance.From the php manual
Here is the result comparing to other 3 methods in update 30,000 raw. Code can be found here which is based on answer from @Dakusan
Transaction: 5.5194580554962
Insert: 0.20669293403625
Case: 16.474853992462
Multi: 0.0412278175354
As you can see, multiple statements query is more efficient than the highest answer.
If you get error message like this:
You may need to increase the
max_allowed_packet
in mysql config file which in my machine is/etc/mysql/my.cnf
and then restart mysqld.使用临时表
Use a temporary table
这应该对你有用。
MySQL 手册中有关于多个表的参考。
This should work for ya.
There is a reference in the MySQL manual for multiple tables.
以下所有内容均适用于 InnoDB。
我觉得了解 3 种不同方法的速度很重要。
有 3 种方法:
我刚刚测试了这一点,并且 INSERT对我来说,方法比 TRANSACTION 方法快 6.7 倍 [使用准备好的事务语句将其时间缩短了约 20%]。 我尝试了一组 3,000 行和 30,000 行。
TRANSACTION 方法仍然必须运行每个单独的查询,这需要时间,尽管它在执行时将结果批量存储在内存或其他内容中。 TRANSACTION 方法在复制和查询日志中也相当昂贵。
更糟糕的是,CASE 方法比包含 30,000 条记录的 INSERT 方法慢 41.1 倍(比 TRANSACTION 慢 6.1 倍)。 MyISAM 中的速度75 倍慢。 INSERT 和 CASE 方法在约 1,000 条记录时实现收支平衡。 即使有 100 条记录,CASE 方法也快不了多少。
所以总的来说,我觉得 INSERT 方法是最好的,也是最容易使用的。 这些查询更小、更易于阅读,并且仅占用 1 个操作查询。 这适用于 InnoDB 和 MyISAM。
额外的东西:
INSERT 非默认字段问题的解决方案是暂时关闭相关的 SQL 模式:
SET SESSION sql_mode=REPLACE(REPLACE(@@SESSION.sql_mode,"STRICT_TRANS_TABLES) ",""),"STRICT_ALL_TABLES","")
。 如果您打算恢复sql_mode
,请务必先保存它。至于我看到的其他评论说使用 INSERT 方法 auto_increment 上升,这似乎是 InnoDB 中的情况,但不是 MyISAM 中的情况。
运行测试的代码如下。 它还输出 .SQL 文件以消除 php 解释器开销
All of the following applies to InnoDB.
I feel knowing the speeds of the 3 different methods is important.
There are 3 methods:
I just tested this, and the INSERT method was 6.7x faster for me than the TRANSACTION method [using prepared statements with the transactions lowered its time by ~20%]. I tried on a set of both 3,000 and 30,000 rows.
The TRANSACTION method still has to run each individually query, which takes time, though it batches the results in memory, or something, while executing. The TRANSACTION method is also pretty expensive in both replication and query logs.
Even worse, the CASE method was 41.1x slower than the INSERT method w/ 30,000 records (6.1x slower than TRANSACTION). And 75x slower in MyISAM. INSERT and CASE methods broke even at ~1,000 records. Even at 100 records, the CASE method is BARELY faster.
So in general, I feel the INSERT method is both best and easiest to use. The queries are smaller and easier to read and only take up 1 query of action. This applies to both InnoDB and MyISAM.
Bonus stuff:
The solution for the INSERT non-default-field problem is to temporarily turn off the relevant SQL modes:
SET SESSION sql_mode=REPLACE(REPLACE(@@SESSION.sql_mode,"STRICT_TRANS_TABLES",""),"STRICT_ALL_TABLES","")
. Make sure to save thesql_mode
first if you plan on reverting it.As for other comments I've seen that say the auto_increment goes up using the INSERT method, this does seem to be the case in InnoDB, but not MyISAM.
Code to run the tests is as follows. It also outputs .SQL files to remove php interpreter overhead
不知道为什么还没有提到另一个有用的选项:
Not sure why another useful option is not yet mentioned:
这个问题很老了,但我想用另一个答案来扩展这个话题。
我的观点是,实现它的最简单方法就是用一个事务包装多个查询。 接受的答案 INSERT ... ON DUPLICATE KEY UPDATE 是一个很好的技巧,但应该意识到它的缺点和限制:
"Field 'fieldname' does not have a default value"
MySQL 警告,即使你根本不插入任何一行。 如果您决定严格并将 mysql 警告转变为应用程序中的运行时异常,那么它会给您带来麻烦。我对三个建议的变体进行了一些性能测试,包括 INSERT ... ON DUPLICATE KEY UPDATE 变体、带有“case / when / then”子句的变体以及简单的事务方法。 您可以在此处获取Python代码和结果。 总体结论是,带有 case 语句的变体速度是其他两个变体的两倍,但为其编写正确且注入安全的代码相当困难,因此我个人坚持最简单的方法:使用事务。
编辑: Dakusan 的调查结果证明我的性能估计不太有效。 请参阅此答案进行另一项更详细的研究。
The question is old, yet I'd like to extend the topic with another answer.
My point is, the easiest way to achieve it is just to wrap multiple queries with a transaction. The accepted answer
INSERT ... ON DUPLICATE KEY UPDATE
is a nice hack, but one should be aware of its drawbacks and limitations:"Field 'fieldname' doesn't have a default value"
MySQL warning even if you don't insert a single row at all. It will get you into trouble, if you decide to be strict and turn mysql warnings into runtime exceptions in your app.I made some performance tests for three of suggested variants, including the
INSERT ... ON DUPLICATE KEY UPDATE
variant, a variant with "case / when / then" clause and a naive approach with transaction. You may get the python code and results here. The overall conclusion is that the variant with case statement turns out to be twice as fast as two other variants, but it's quite hard to write correct and injection-safe code for it, so I personally stick to the simplest approach: using transactions.Edit: Findings of Dakusan prove that my performance estimations are not quite valid. Please see this answer for another, more elaborate research.
是的,这是可能的 - 您可以使用 INSERT ... ON DUPLICATE KEY UPDATE。
使用你的例子:
Yes, that's possible - you can use INSERT ... ON DUPLICATE KEY UPDATE.
Using your example:
由于您有动态值,因此需要对要更新的列使用 IF 或 CASE。 它变得有点难看,但它应该可以工作。
使用您的示例,您可以这样做:
Since you have dynamic values, you need to use an IF or CASE for the columns to be updated. It gets kinda ugly, but it should work.
Using your example, you could do it like:
现在简单的方法
And now the easy way