我希望優化下面的查詢,該查詢具有來自關系表的子查詢,并且對子查詢計數資料進行排序。請參閱以下查詢:
SELECT table1.*,
( SELECT COUNT(*)
FROM table2
WHERE table2.user_id=table1.id
AND table2.deleted = 0) AS table2_total
FROM table1
WHERE table1.parent_id = 0
ORDER BY table2_total DESC LIMIT 0, 50
此查詢運行良好,但當 table2 的資料超過 50K 時它會卡住。我也嘗試使用左連接而不是子查詢,但這更慢:
SELECT table1.*,
COUNT(DISTINCT table2.id) as table2_total
FROM table1
LEFT JOIN table2 ON table2.user_id=table1.id
AND table2.deleted = 0
WHERE table1.parent_id = 0
ORDER BY table2_total DESC LIMIT 0, 50
table2 已經在 user_id 和已洗掉列上有索引。請看下表2結構:

有沒有辦法以更好的方式優化這個查詢?
uj5u.com熱心網友回復:
它應該是這樣的:
select table1.*, count(*) as table2_total from table1, table2
where table1.id = table2.user_id
and table1.parent_id = 0
and table2.deleted = 0
group by table1.id
order by table2_total desc
limit 50
請注意,單獨的索引 ondeleted將無濟于事,只有復合索引((deleted, user_id)或(user_id, deleted),取決于您的資料)可以提供幫助(user_id如果洗掉的行百分比較低,則與 on 的單個索引相比甚至沒有顯著差異)。
uj5u.com熱心網友回復:
您可以嘗試將索引添加到 table2.deleted 和 table1.parent_id 列。該索引將影響插入的性能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/422489.html
標籤:
