订单表建立了一个联合索引 index_order_store: [ store_id
, create_time
]
查询:
SELECT * FROM orders WHERE store_id = 100001 ORDER BY orders.create_time DESC LIMIT 0,2
EXPLAIN 显示扫描了店铺的所有订单(扫描了 14 行),并没有使用索引排序。
SIMPLE orders ref index_order_store index_order_store 5 const 14 Using where
哪个地方错了
1 ilyh 2019-03-16 12:28:04 +08:00 全表才 14 行数据, mysql 会做优化, 直接全表扫描更快吧 |
3 ilyh 2019-03-16 12:32:57 +08:00 type 为 ref 已经走了索引了啊... |
4 ilyh 2019-03-16 12:37:20 +08:00 估计是 store_id = 100001 就有 14 行吧 |
5 kaid97 2019-03-16 12:46:29 +08:00 ref 就是使用了索引,而且返回值也只有一条 |
![]() | 6 fuxinya OP @ilyh #4 刚刚给店铺 100001 造了 100 条数据,又给另一个店铺也造了 200 条,查询结果:扫描了 100 行。现在的问题是虽然 store_id 走了那个联合索引,但是对 create_time 排序没有使用索引,SQL 语句中限制了条数:LIMIT 0,2。 但是却扫描了 100 行。期望是仅扫描 2 行。 难道是我认知错误了,ORDER BY 永远不会索引? |
8 ilyh 2019-03-16 12:56:31 +08:00 不是 orderby 不走索引, 是 limit 是读到所有匹配行再保留第一行 |
![]() | 9 polythene 2019-03-16 13:28:10 +08:00 用 force index 强制走索引吧 |
![]() | 10 ToTChowChow 2019-03-16 13:29:25 +08:00 via Android SELECT store_id, create.time FROM orders WHERE store_id = 100001 ORDER BY orders.create_time DESC LIMIT 0,2 改成这样? |
![]() | 11 harde 2019-03-16 13:36:57 +08:00 歪个楼。。。。 在做这样的测试时,建议造个几十万条数据。。。 很多时候还是数据库聪明。 |
![]() | 13 constructor 2019-03-17 09:30:55 +08:00 原来和数据量有关系,我之前也有这样的疑问,一度误以为对索引的理解有偏差 |