我有一個數據庫結構與下面的協會服務了新聞報道:提高了許多LEFT一個SQL查詢的性能JOIN的
- HABTM news_categories
- HABTM標籤
- HABTM上傳
我寫了一條SQL查詢將所有這一切拉到一起:
SELECT `news_articles`.*,
GROUP_CONCAT(DISTINCT tags.title) AS `tags`,
GROUP_CONCAT(DISTINCT tags.id) AS `tag_ids`,
GROUP_CONCAT(DISTINCT news_categories.title) AS `news_categories`,
GROUP_CONCAT(DISTINCT news_categories.id) AS `news_category_ids`,
GROUP_CONCAT(DISTINCT news_categories.slug) AS `news_category_slugs`,
`news_articles_uploads`.`caption` AS `upload_caption`,
`uploads`.`title` AS `upload_title`,
`uploads`.`basename` AS `upload_basename`,
`uploads`.`extension` AS `upload_extension`,
`uploads`.`path` AS `upload_path`
FROM `news_articles`
LEFT JOIN `news_articles_tags` ON news_articles_tags.news_article_id = news_articles.id
LEFT JOIN `tags` ON news_articles_tags.tag_id = tags.id
LEFT JOIN `news_articles_news_categories` ON news_articles_news_categories.news_article_id = news_articles.id
LEFT JOIN `news_categories` ON news_articles_news_categories.news_category_id = news_categories.id
LEFT JOIN `news_articles_uploads` ON (news_articles_uploads.news_article_id = news_articles.id AND news_articles_uploads.order = 0)
LEFT JOIN `uploads` ON news_articles_uploads.upload_id = uploads.id
WHERE (news_categories.slug IN ("category-one","category-two","category-three","category-four","category-five")) AND (news_articles.published = 1)
GROUP BY `news_articles`.`id`
ORDER BY `news_articles`.`lead_article` DESC, `news_articles`.`created` DESC LIMIT 20;
問題是,在查詢運行時,速度很慢,而在繁忙時段,CPU使用率變得非常不可收拾!
下面是一個解釋上面的查詢(右鍵單擊在新標籤中打開看原圖):
你可以在這裏找到的模式:http://pastie.org/private/qoe2qo16rbqr5mptb4bug
的服務器運行MySQL 5.1.55,網站使用Zend Framework來執行查詢和PHP 5.2.8。
我已經通過MySQL慢速查詢日誌,並添加了我所知道的最好的缺失索引,但查詢仍顯示爲需要1-3秒才能執行。如果有人有任何想法,我非常感激。提前致謝。
謝謝,我會放棄這個! – BeesonBison 2012-02-24 17:49:04