下面的查询有什么区别? id为主键
1, select id from tbl_xxx WHERE 2708 <= id <= 1562755185;
2, select id from tbl_xxx WHERE id> = 2708 and id <= 1562755185;
3, select id from tbl_xxx WHERE id between 2708 and 1562755185;
我发现性能不同,但不知道为什么?
explain select id from tblData WHERE id >= 2708 and id <= 1562755185 ORDER BY id asc LIMIT 652000, 1000\G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: tblData
type: range
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: NULL
rows: 30461948
Extra: Using where; Using index
explain select id from tblData WHERE 2708 <= id <= 1562755185 ORDER BY id asc LIMIT 652000, 1000\G; *************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: tblData
type: index
possible_keys: NULL
key: PRIMARY
key_len: 4
ref: NULL
rows: 653000
Extra: Using where; Using index
最佳答案
查询2和3是等效的,因此它们应该执行相同的操作。查询1是完全不同的东西;查询 1 相当于:
select id from tbl_xxx WHERE (2708 <= id) <= 1562755185;
自 2708 <= id
是一个 bool 表达式,MySQL 使用零和一作为 bool 值,你的查询总是比较 1 <= 1562755185
或0 <= 1562755185
因此退化为:
select id from tbl_xxx;
假设id
当然永远不会是NULL。
因此,查询完全不同,没有理由期望它们执行相同的操作。
例如,我有一张 table ,看起来像这样:
mysql> select * from stars;
+----+-------+
| id | stars |
+----+-------+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 2 |
| 5 | 1 |
| 6 | 1 |
| 7 | 1 |
| 8 | 2 |
| 9 | 1 |
+----+-------+
一个between
这样做:
mysql> select * from stars where id between 3 and 5;
+----+-------+
| id | stars |
+----+-------+
| 3 | 3 |
| 4 | 2 |
| 5 | 1 |
+----+-------+
但是你的a <= id <= b
这样做:
mysql> select * from stars where 3 <= id <= 5;
+----+-------+
| id | stars |
+----+-------+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 2 |
| 5 | 1 |
| 6 | 1 |
| 7 | 1 |
| 8 | 2 |
| 9 | 1 |
+----+-------+
关于mysql查询不同,性能不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9347344/