原始SQL(平均执行时间2s+)
SELECT DISTINCT
sid
FROM
test
WHERE
cid = 123456
AND (
(eid = 7890123)
OR sid IN (
SELECT
sid
FROM
test
WHERE
cid = 123456
GROUP BY
sid
HAVING
COUNT(*) = 1
)
)
430万+数据量的表,索引如下:
KEY idx_eid (eid)
KEY index_0 (cid,type)
KEY index_1 (sid,type,eid)
KEY idx_cs (cid,sid)
优化后SQL(平均执行时间400ms左右)
SELECT DISTINCT sid FROM test WHERE cid = 900458 AND eid = 1021355
union
SELECT sid FROM test WHERE cid = 900458 GROUP BY sid HAVING COUNT(*) = 1
说明:
mysql版本5.6.28
优化前,test和子查询都使用的idx_cs索引,cid 的基数不如eid,所以拆开后第一个test 使用eid索引,第二次使用的idx_cs
本文由博客一文多发平台 OpenWrite 发布!