2011-09-07 53 views
0

我有一個表「事件」和幾個關節表計數項目如下:MySQL的:在許多連接表

活動 +標籤 +圖像 +視頻

我想能夠形成一個查詢,在那裏我可以計算聯合表中的項目,如果有的話。所以我有這樣的:

SELECT t.*, COUNT(distinct t1.id) visible_tags, COUNT(distinct t2.id) 
     invisible_tags, ..., COUNT(distince tn.id) approved_videos 
FROM events t 
LEFT JOIN tags t1 ON ... 
LEFT JOIN tags t2 ON ... 
LEFT JOIN tags t3 ON ... 
... 
LEFT JOIN videos tn ON ... 

問題是,查詢即使所有的索引需要相當長的時間。有沒有辦法如何形成它不同?

謝謝。

回答

1

除了@sanmai關於'說明選擇'的說明,您還可以加入子查詢。

SELECT t.*, t1_count, t2_count 
FROM events t 
LEFT JOIN (select count(distinct id) as t1_count from tags) as t1 
LEFT JOIN (select count(distinct id) as t2_count from tags) as t2 
... 
1

如果查詢需要很長時間的機會,問題不在查詢中。

此查詢使用了哪些索引?請展示使用EXPLAIN SELECT ...