[英]MySQL Query optimization with JOIN and COUNT
我有以下 MySQL 查詢:
SELECT t1.id, t1.releaseid, t1.site, t1.date, t2.pos FROM `tracers` as t1
LEFT JOIN (
SELECT `releaseid`, `date`, COUNT(*) AS `pos`
FROM `tracers` GROUP BY `releaseid`
) AS t2 ON t1.releaseid = t2.releaseid AND t2.date <= t1.date
ORDER BY `date` DESC , `pos` DESC LIMIT 0 , 100
想法是將 select 發布並計算在記錄日期之前有多少其他網站也發布了它,以獲得 position。
解釋說:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY t1 ALL NULL NULL NULL NULL 498422 Using temporary; Using filesort
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 91661
2 DERIVED tracers index NULL releaseid 4 NULL 498422
關於如何消除 Using 臨時的任何建議; 使用文件排序? 這需要很長時間。 我想到並嘗試過的索引沒有任何幫助。
下面的這個答案可能不會改變解釋 output,但是如果您的主要問題是排序數據,它通過刪除 order 子句確定將使您的查詢運行得更快,請先嘗試對您的子查詢連接表進行排序,您的查詢將是:
SELECT t1.id, t1.releaseid, t1.site, t1.date, t2.pos FROM `tracers` as t1
LEFT JOIN (
SELECT `releaseid`, `date`, COUNT(*) AS `pos`
FROM `tracers` GROUP BY `releaseid`
ORDER BY `pos` DESC -- additional order
) AS t2 ON t1.releaseid = t2.releaseid AND t2.date <= t1.date
ORDER BY `date` DESC , `pos` DESC LIMIT 0 , 100
注意:我的數據庫版本是 mysql-5.0.96-x64,也許在另一個版本中你會得到不同的結果。
嘗試在tracers.date
上添加一個索引,在tracers.releaseid
上添加一個
嘗試有兩個索引,一個在(date)
上,一個在(releaseid, date)
上。
另一件事是您的查詢似乎沒有按照您的描述進行。 它實際上計算正確嗎?
嘗試將其重寫為:
SELECT t1.id, t1.releaseid, t1.site, t1.`date`
, COUNT(*) AS pos
FROM tracers AS t1
JOIN tracers AS t2
ON t2.releaseid = t1.releaseid
AND t2.`date` <= t1.`date`
GROUP BY t1.releaseid
ORDER BY t1.`date` DESC
, pos DESC
LIMIT 0 , 100
或作為:
SELECT t1.id, t1.releaseid, t1.site, t1.`date`
, ( SELECT COUNT(*)
FROM tracers AS t2
WHERE t2.releaseid = t1.releaseid
AND t2.`date` <= t1.`date`
) AS pos
FROM tracers AS t1
ORDER BY t1.`date` DESC
, pos DESC
LIMIT 0 , 100
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.