简体   繁体   English

与条件较少的sql相比,条件更多的sql更快吗?

[英]Is sql with more where condition faster than those with less in mysql?

I hava big table need to be queried by a datetime column every 5 minutes. 我有一个大表需要每隔5分钟由datetime列查询一次。

My solution is like this: 我的解决方案是这样的:

select * from tbl_name where datetime_col < '2019-05-26 20:49:00' and tag_col = 0;

,and do something with the result set,and if the "something" succeeds,then update the row and set the tag_col to 1. ,然后对结果集进行操作,如果“操作”成功,则更新行并将tag_col设置为1。

One of my colleague has a solution like this: 我的一位同事有这样的解决方案:

select * from tbl_name where datetime_col < '2019-05-26 20:49:00' and datetime_col >= '2019-05-26 20:44:00' and tag_col = 0;

,and do something with the result set,and if the "something" fails,update the row and add 5 minutes to the datetime_col(so that it will be selected next time),and if the "something" succeeds,also update the row and set the tag_col to 1. ,然后对结果集执行某些操作,如果“某事”失败,请更新该行,并在datetime_col中添加5分钟(以便下次选择该行),如果“某事”成功,则也请更新该行并将tag_col设置为1。

My question is whose sql is faster (or they are equally fast) when there is index on the datetime_col? 我的问题是,当datetime_col上有索引时,谁的sql更快(或它们也同样快)? Thanks. 谢谢。

If you execute this query: 如果执行此查询:

select *
from tbl_name
where datetime_col < '2019-05-26 20:49:00'

You are presumably going to be returns lots and lots of data, because -- by your description -- you have a "big table". 大概您将要返回很多数据,因为按照您的描述,您有一个“大表”。 You then have to forage through this to get the results you want. 然后,您必须仔细检查以获取所需的结果。

If you execute: 如果执行:

select *
from tbl_name
where datetime_col < '2019-05-26 20:49:00'
order by datetime_col desc;

Then I think MySQL will use the index and be able to return the rows that you want. 然后,我认为MySQL将使用索引并能够返回所需的行。 However, you are still returning lots and lots of rows. 但是,您仍然返回很多行。 You should test if the performance is okay. 您应该测试性能是否还可以。

Your colleague's query is: 您的同事的查询是:

select *
from tbl_name
where datetime_col < '2019-05-26 20:49:00' and
      datetime_col >= '2019-05-26 20:44:00';'

This returns only the rows you want -- presumably a much smaller set. 这仅返回您想要的行-可能是更小的集合。 It should use the index to find those rows. 它应该使用索引来查找那些行。

I would expect that your colleague is correct. 我希望你的同事是正确的。 Even if the rows don't exist and you have to issue another query, that is probably faster than returning almost the entire table. 即使行不存在并且您必须发出另一个查询,也可能比返回几乎整个表更快。

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

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