我在下面有這個查詢,表中只有大約 200k 條記錄,這個查詢開始花費太長時間來執行。大約30秒左右。
我不確定導致問題的原因或原因。
我有其他資料庫,有超過 200 萬條記錄,沒有速度問題。
但不知何故,由于某種原因,這個查詢在網站上引起了問題。
select p.pid, p.other_fields, c.user_name,
group_concat( t.tag ) as tags
from post_table as p, user_table as c, tag_table as t
where p.userID= c.userID
and p.stat=1
and p.mainID=0
and c.stat='y'
and t.pid=p.pid
group by p.pid
order by p.pid desc
limit 0, 20
這是同一查詢的正確 JOIN 格式,沒有區別,仍然很慢。下面這實際上是我之前的,但后來將其更改為上述舊格式,只是為了嘗試是否有任何不同。
select p.pid, p.other_fields, c.user_name, group_concat( t.tag ) as tags
from post_table as p
LEFT JOIN user_table as c on p.userID = c.userID
LEFT JOIN tag_table as t on p.pid = t.pid
where p.stat=1
and p.mainID=0
and c.stat='y'
group by p.pid
order by p.pid desc
limit 0, 20
這些表的結構和索引:
post_table:
pid, userID, stat, mainID, title, other_fields...
index( userID, stat, mainID, title )
User_table:
userID, stat, user_name, pass_word, etc...
index( user_name, pass_word )
index( stat )
tag_table:
id, pid, tag
index( pid, tag )
我想我正確地跟蹤了所有索引,但查詢仍然需要很多時間來執行,我不知道為什么。
有人可以告訴我可能是什么原因嗎?謝謝
下面是上面這個查詢的 EXPLAIN 陳述句的輸出:
But I am not sure what this is doing, however, I think that for some reason its ignoring the "stat" index on both user_table and post_table.
3 in array
Array
(
[0] => Array
(
[id] => 1
[select_type] => SIMPLE
[table] => c
[type] => ALL
[possible_keys] => PRIMARY,id,id_2, userStat
[key] =>
[key_len] =>
[ref] =>
[rows] => 8
[Extra] => Using where; Using temporary; Using filesort
)
[1] => Array
(
[id] => 1
[select_type] => SIMPLE
[table] => p
[type] => ref
[possible_keys] => PRIMARY,id,id_2, userID, postmainID
[key] => userID
[key_len] => 27
[ref] =>
[rows] => 15091
[Extra] =>
)
[2] => Array
(
[id] => 1
[select_type] => SIMPLE
[table] => t
[type] => ref
[possible_keys] => pid
[key] => pid
[key_len] => 777
[ref] =>
[rows] => 1
[Extra] => Using where; Using index
)
)
uj5u.com熱心網友回復:
select p.pid, p.other_fields, c.user_name,
( SELECT group_concat( t.tag ) FROM tag_table AS t
WHERE t.pid = p.pid ) as tags
FROM post_table as p
JOIN user_table as c ON p.userID = c.userID
where p.stat = 1
and p.mainID = 0
and c.stat = 'y'
order by p.pid desc
limit 0, 20
p: INDEX(stat, mainID, pid, userID, other_fields)
c: INDEX(userID, stat, user_name)
t: INDEX(pid, tag)
的GROUP BY p.pid可能是現在多余的,把它放回如果你需要它。
沒有表現老逗號連接和新的之間的差異JOIN..ON。還有一個可能的語意之間的差異JOIN/逗號連接和LEFT JOIN。我的重新公式tags相當于LEFT JOIN. 的存在c.stat = ...迫使對方LEFT JOIN變成JOIN,所以沒有語意差異。
pid是 key_len=777 嗎?請提供SHOW CREATE TABLE以便我理解。userID和 27同上。
優化器避免給定索引的可能原因有很多。它可能會優先使用我的索引而不是所有其他索引。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/342403.html
標籤:mysql
