哪两个查询会更快?

Yad*_*ada 1 sql query-optimization

SELECT * FROM table WHERE col IN (1,2,3)
Run Code Online (Sandbox Code Playgroud)

要么

SELECT * FROM table WHERE col = 1 OR col = 2 OR col = 3
Run Code Online (Sandbox Code Playgroud)

che*_*vim 5

他们是一样的.

编辑:它们在MySQL中是相同的.

使用索引:

mysql> explain select * from trees where id = 1 or id = 2;
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
|  1 | SIMPLE      | trees | range | PRIMARY       | PRIMARY | 8       | NULL |    2 | Using where |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+

mysql> explain select * from trees where id in (1,2);
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
|  1 | SIMPLE      | trees | range | PRIMARY       | PRIMARY | 8       | NULL |    2 | Using where |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
Run Code Online (Sandbox Code Playgroud)

使用全表扫描:

mysql> explain select * from trees where version = 1 or version = 2;
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra       |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
|  1 | SIMPLE      | trees | ALL  | NULL          | NULL | NULL    | NULL |    7 | Using where |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+

mysql> explain select * from trees where version in (1,2);
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra       |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
|  1 | SIMPLE      | trees | ALL  | NULL          | NULL | NULL    | NULL |    7 | Using where |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
Run Code Online (Sandbox Code Playgroud)

  • 在执行计划方面似乎不太可能.这取决于DBMS如何决定优化查询. (2认同)