![Uploading file…]()
原始 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