[英]Mysql join with group by query optimization
我使用以下查詢來獲取最新文章(文章標題+作者姓名+總評論),但運行需要很長時間:
SELECT article.id, title, username, count( comment.id ) AS total_comments
FROM article
LEFT JOIN COMMENT ON comment.article_id = article.id
LEFT JOIN user ON article.user_id = user.id
WHERE STATUS = "open"
AND section = "mobiles"
GROUP BY article.id
ORDER BY article.id DESC
LIMIT 0 , 30
解釋的輸出是:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE article ALL status NULL NULL NULL 77 Using where; Using temporary; Using filesort
1 SIMPLE comment ref article_id article_id 5 test.article.id 2
1 SIMPLE user eq_ref PRIMARY PRIMARY 4 test.article.user_id 1
如何重新編寫查詢以避免創建臨時表?
存儲引擎是MyISAM。 這是帶索引的表詳細信息:
article
id, title, body, user_id, status, section
primary key: id
indexes: (user_i),(status,section,id)
comment
id, article_id, user_id, body
primary key: id
index:(article_id)
user
id, username
primary key: id
這個執行計划非常好。 你真的無法避免創建和排序臨時表:你的查詢調用分組和排序的摘要,嗯,一個臨時表。 如果為mySQL服務器進程提供更多RAM,則可以使用內存表而不是磁盤表。
使用子查詢而不是分組連接會加快進程。
SELECT article.id, title, username,
(
select count(*) from COMMENT
where comment.article_id = article.id
) AS total_comments
FROM article
LEFT JOIN user ON article.user_id = user.id
WHERE STATUS = "open"
AND section = "mobiles"
ORDER BY article.id DESC
LIMIT 0 , 30
按照上一個問題如何進行嵌套查詢?
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.