SELECT ... WHERE COL IN(A,B)
or
SELECT ... WHERE (COL = A or COL = B)
我试图找出这两种结构之间的区别是什么?
如果用于接近100万标记的结果集,是否会有显着的性能提升?
答案 0 :(得分:7)
mysql> describe select * from users where id = 1 or id = 2;
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
| 1 | SIMPLE | users | range | PRIMARY | PRIMARY | 4 | NULL | 2 | Using where |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
1 row in set (0.01 sec)
mysql> describe select * from users where id in (1,2);
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
| 1 | SIMPLE | users | range | PRIMARY | PRIMARY | 4 | NULL | 2 | Using where |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
1 row in set (0.00 sec)
从DESCRIBE
陈述的输出来看 - 它们是相同的。
答案 1 :(得分:1)
使用
之间没有性能差异col = A or col = B
和
col IN (8,7,5,2,....)
mysql范围优化器通过计算(8,7,5,2,....)的排序列表来优化IN查询,然后使用它来构造相应的SEL_TREE。
所以没有性能差异,因为两者都会对索引进行范围扫描。
答案 2 :(得分:0)
就像一个小例子:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.1.41-community-log MySQL Community Server (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> SET @qwe=5;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT BENCHMARK(100000000, @qwe IN (10,5));
+--------------------------------------+
| BENCHMARK(100000000, @qwe IN (10,5)) |
+--------------------------------------+
| 0 |
+--------------------------------------+
1 row in set (3.52 sec)
mysql> SELECT BENCHMARK(100000000, @qwe = 10 OR @qwe = 5);
+---------------------------------------------+
| BENCHMARK(100000000, @qwe = 10 OR @qwe = 5) |
+---------------------------------------------+
| 0 |
+---------------------------------------------+
1 row in set (5.91 sec)
和
mysql> SELECT BENCHMARK(100000000, @qwe IN (10,1,9,2,8,3,7,4,6,5));
+------------------------------------------------------+
| BENCHMARK(100000000, @qwe IN (10,1,9,2,8,3,7,4,6,5)) |
+------------------------------------------------------+
| 0 |
+------------------------------------------------------+
1 row in set (6.02 sec)
mysql> SELECT BENCHMARK(100000000, @qwe = 10 OR @qwe = 1 OR @qwe = 9
-> OR @qwe = 2 OR @qwe = 8 OR @qwe = 3 OR @qwe = 7 OR @qwe = 4
-> OR @qwe = 6 OR @qwe = 5) as result;
+--------+
| result |
+--------+
| 0 |
+--------+
1 row in set (20.20 sec)
注意括号中的持续时间。