2013-03-13 62 views
0

有一個是這兩個查詢組合成一個查詢,這樣的結果是:SQL:SUM計數和集團合併查詢

ChannelId | ContentType | ContentTypeCount | SumOfAllContentTypes 
    100  | link  | 59    | 179 
    100  | photo  | 49    | 179 
    100  | status  | 2    | 179 
    100  | video  | 4    | 179 
    101  | link  | 15    | 179 
    101  | status  | 50    | 179 

下面是我使用目前的查詢:

SELECT 
COUNT(posts.id) 
FROM posts 
INNER JOIN channels ON channels.id = posts.channel_id 
WHERE channels.site_id = 1003 
AND channels.channel_type_id = 1 

結果= 179

和..

SELECT 
posts.channel_id, 
posts.contenttype, 
COUNT(posts.contenttype) as contenttypecount 
FROM posts 
INNER JOIN channels ON channels.id = posts.channel_id 
WHERE channels.site_id = 1003 
AND channels.channel_type_id = 1 
GROUP BY posts.channel_id, posts.contenttype 

result = 100 |鏈接| 59;等。

在此先感謝您的幫助。

+0

很可能,但你爲什麼要?兩個查詢都使用不相互適用的不同條件。它就像是想要一個蘋果和橘子,並要求將它們組合成一個單子。 – 2013-03-13 18:46:35

+0

您可以再次「加入帖子」,但是_why_是否會將數據庫強調爲您已明確得到的內容? – Wrikken 2013-03-13 18:47:54

+0

@MarcB:我們是否應該真的判斷OP所陳述的商業要求? – 2013-03-13 18:52:29

回答

2

試試這個:

select A.*, B.* 
from (
    SELECT 
    posts.channel_id, 
    posts.contenttype, 
    COUNT(posts.contenttype) as contenttypecount 
    FROM posts 
    INNER JOIN channels ON channels.id = posts.channel_id 
    WHERE channels.site_id = 1003 
    AND channels.channel_type_id = 1 
    GROUP BY posts.channel_id, posts.contenttype 
) A 
join (
    SELECT 
    COUNT(posts.id) as Total 
    FROM posts 
    INNER JOIN channels ON channels.id = posts.channel_id 
    WHERE channels.site_id = 1003 
    AND channels.channel_type_id = 1 
) B on 1=1 

不是特別有效,但容易和簡單。

+0

謝謝親切的彼得。該查詢工作並在0.0027秒內返回結果。 – Jim 2013-03-13 18:59:40