我有一张大表,需要每 5 分钟通过日期时间列进行查询。
我的解决方案是这样的:
select * from tbl_name where datetime_col < '2019-05-26 20:49:00' and tag_col = 0;
,并对结果集执行某些操作,如果“某些操作”成功,则更新该行并将 tag_col 设置为 1。
我的一位同事有这样的解决方案:
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;
,并对结果集执行某些操作,如果“某事”失败,则更新该行并向 datetime_col 添加 5 分钟(以便下次选择),如果“某事”成功,也更新该行并将 tag_col 设置为 1。
我的问题是,当 datetime_col 上有索引时,谁的 sql 更快(或者它们同样快)? 谢谢。
最佳答案
如果执行此查询:
select *
from tbl_name
where datetime_col < '2019-05-26 20:49:00'
您可能会返回大量数据,因为根据您的描述,您有一个“大表”。然后你必须通过这个来获得你想要的结果。
如果执行:
select *
from tbl_name
where datetime_col < '2019-05-26 20:49:00'
order by datetime_col desc;
然后我认为MySQL将使用索引并能够返回你想要的行。但是,您仍然返回很多很多行。您应该测试性能是否正常。
您同事的查询是:
select *
from tbl_name
where datetime_col < '2019-05-26 20:49:00' and
datetime_col >= '2019-05-26 20:44:00';'
这仅返回您想要的行——可能是一个小得多的集合。它应该使用索引来查找这些行。
我希望你的同事是正确的。即使这些行不存在并且您必须发出另一个查询,这可能比返回几乎整个表要快。
关于mysql - mysql中where条件多的sql是否比mysql中条件少的sql快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56313738/