简体   繁体   English

mysql UPDATE,性能WHERE检查vs不检查

[英]mysql UPDATE, performance WHERE check vs no check

I have a very long table that has 10000 rows. 我有一个非常长的表,具有10000行。 9500 rows have a column set to 1 and the remaining 500 have that column set to 0. I want to update the table so all rows have that column set to 1. 9500行的列设置为1,其余500的列设置为0。我想更新表,以便所有行的列设置为1。

Would it be faster to use WHERE column = 0 or is it better to skip the WHERE and just UPDATE all ? 使用WHERE column = 0会更快吗?或者跳过WHERE并仅更新全部会更好吗? Im using a prepared statement. 我正在使用准备好的声明。

  • thanks 谢谢

This is an interesting question. 这是个有趣的问题。 In general, I would say it is better to have where column = 0 . 通常,我想说where column = 0更好。 It should never be detectably worse, but in MySQL it might not make a difference. 它永远不会恶化到可察觉的水平,但是在MySQL中却可能没有什么不同。

With no index on the column, then the query will need to read all the rows anyway in order to identify the ones that need to be updated. 在列上没有索引的情况下,查询将仍然需要读取所有行,以标识需要更新的行。 So, the query is going to do a full table scan regardless. 因此,无论如何查询都将进行全表扫描。 Even with an index, the optimizer may still choose a full table scan, unless you have a clustered index on column . 即使具有索引,优化器仍可能选择全表扫描,除非您在column上具有聚集索引。

Then, the overhead on doing an update is maintaining the log. 然后,进行更新的开销就是维护日志。 I'm pretty sure that MySQL only logs actual changes to the database. 我很确定MySQL仅将实际更改记录到数据库中。 In other words, it is doing the comparison anyway. 换句话说,它还是在进行比较。 So, MySQL is not going to "re-update" values to the same value. 因此,MySQL不会将值“重新更新”为相同的值。 Note: not all databases behave this way. 注意:并非所有数据库都以这种方式运行。

All that said, I would always put the where column = 0 if that is your intention. 话虽如此,如果您打算这样做,我将始终将where column = 0 On 10,000 rows, performance isn't the big issue. 在10,000行中,性能不是大问题。 Clarity of code ranks higher, in my opinion. 我认为代码的清晰度更高。 Also, I write code for multiple databases, so I prefer to write code that will work well across all of them. 另外,我为多个数据库编写代码,所以我更喜欢编写在所有数据库上都能正常工作的代码。

With my script execution time measurements, for the MariaDB it's pretty much the same result with that queries (I mean result & time). 通过我的脚本执行时间测量,对于MariaDB,该查询的结果几乎相同(我的意思是结果和时间)。

I will try it on MySQL too. 我也会在MySQL上尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM