mysql where和order by 同时使用时导致索引失效

不好意思,之前时间紧急,导致sql写错了,我现在修正下问题

我创建了两张表,

商户表(merchant)
CREATE TABLE merchant (
merchant_id int NOT NULL AUTO_INCREMENT,
merchant_name varchar(30) DEFAULT NULL,
create_time datetime DEFAULT NULL,
PRIMARY KEY (merchant_id),
KEY idx_create_time (create_time)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

商品表
CREATE TABLE product (
product_id int NOT NULL AUTO_INCREMENT,
product_name varchar(30) DEFAULT NULL,
merchant_id int DEFAULT NULL,
PRIMARY KEY (product_id)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

此时,我想查询查询各个商户近期上架的产品,并提供给前端
EXPLAIN SELECT * FROM merchant m
INNER JOIN product p ON p.merchant_id=m.merchant_id

WHERE m.create_time>'2021-11-10'
ORDER BY m.create_time DESC
LIMIT 0,10

此时,我发现索引并没有生效

img

Group by 后面不应该加条件,应该加列名称,例如你这里就直接跟create_time

你写错了,正确的sql:
SELECT * FROM merchant WHERE create_time>'2021-11-10' ORDER BY create_time asc LIMIT 0,10

ORDER BY后面加列名,因为他是用来排序的

EXPLAIN SELECT * FROM merchant
INNER JOIN product ON merchant.merchant_id=product.merchant_id WHERE merchant.create_time>'2021-11-10' ORDER BY merchant.create_time DESC LIMIT 0,10
试一下

你create_time做索引,where条件中从小到搜索大于2021-11-10的数据,但是你又倒序排,还是得扫描2021-11-10的所有数据,所以索引没什么用。

执行一下这个:

EXPLAIN SELECT
*
FROM
(select merchant_id from merchant order by create_time DESC limit 1,10) a
left join merchant m on a.merchant_id=m.merchant_id
INNER JOIN product p ON p.merchant_id = m.merchant_id
WHERE
m.create_time > '2021-11-10'
ORDER BY
m.create_time DESC
LIMIT 0,10;

参考: