我有posts表,post的状态是tinyint
,可以是1-10之间的数字。我需要选择那些职位,有状态中的这些数字- 6,7,8,9,10。那么,哪种解决方案在性能方面会更好呢
1) SELECT id, title, status FROM posts WHERE status > 5
2) SELECT id, title, status FROM posts WHERE status IN(6, 7, 8, 9, 10)
我没有列出使用OR
,因为从这个答案IN
更快
MYSQL OR vs IN performance
感谢 status
列被索引
看这个小提琴:http://sqlfiddle.com/#!2/346380/3
Select <:
Record Count: 2; Execution Time: 27ms
选择& lt;解释:
ID SELECT_TYPE TABLE TYPE POSSIBLE_KEYS KEY KEY_LEN REF ROWS EXTRA
1 SIMPLE supportContacts range helper helper 5 (null) 2 Using where
选择:
Record Count: 2; Execution Time: 1ms
Select IN explain:
ID SELECT_TYPE TABLE TYPE POSSIBLE_KEYS KEY KEY_LEN REF ROWS EXTRA
1 SIMPLE supportContacts ref helper helper 5 const 2 Using where
正如大多数人所说,TYPE ref
将比range
更快。所以我相信后者会更快。
使用Explain编写更好的SQL查询
我希望in子句稍微快一点,因为它可以使用给定的值作为索引的直接键,从而使用行。
使用GT将至少有一个额外的操作来确定所有的键。
但是majimboos的方法是慷慨的:使用EXPLAIN来查看在具体情况下会发生什么