2011-07-11 106 views
1

我有2個表(maintable和categorytable)SQL表連接的另一個表

maintable記錄:

categoryCode field2 field3 

1    XXXXXX1 ACTIVE 
3    XXXXXX2 ACTIVE 
1    XXXXXX3 ACTIVE 
1    XXXXXX4 ACTIVE 
3    XXXXXX5 ACTIVE 
3    XXXXXX5 NOT ACTIVE 

categorytable記錄:

categoryCode  categoryname 

1     categoryname1 
2     categoryname2 
3     categoryname3 

到目前爲止,我有這個疑問

SELECT COUNT(*) AS recordcount, 
     categoryCode AS catCode, 
     categorytable.categoryname 
    FROM maintable, 
     categorytable 
    WHERE categorytable.categoryCode = maintable.categoryCode 
    AND maintable.field3 = 'ACTIVE' 
GROUP BY maintable.categoryCode 
ORDER BY categorytable.categoryCode 

with下面的輸出

recordcount catCode categoryname 
---------------------------------- 
3   1  categoryname1 
2   3  categoryname3 

但我需要的輸出是這樣的(0記錄類別中包括顯示爲0的RecordCount):

recordcount catCode categoryname 
3   1  categoryname1 
0   2  categoryname2 
2   3  categoryname3 

回答

0

您需要使用左連接:

SELECT COUNT(*) AS recordcount, categoryCode AS catCode, categorytable.categoryname 
FROM categorytable 
LEFT JOIN maintable ON categorytable.categoryCode = maintable.categoryCode 
GROUP BY maintable.categoryCode 
ORDER BY categorytable.categoryCode 

如果你不想扭轉表名,請參閱AlexanderMP的答案。

+0

我敢打賭,你的意思是寫 「RIGHT JOIN」。 – AlexanderMP

+0

@AlexanderMP - 無論哪種方式,結果都是一樣的。 – Cfreak

+0

您的查詢顯示的是相同的輸出(0個記錄數沒有顯示的類別) – Bert

3
SELECT 
    coalesce(COUNT(maintable.categoryCode),0) AS recordcount, 
    categorytable.categoryCode AS catCode, 
    categorytable.categoryname 
FROM 
    maintable 
RIGHT JOIN categorytable ON categorytable.categoryCode = maintable.categoryCode 
GROUP BY 
    categorytable.categoryCode, 
    categorytable.categoryname 
ORDER BY 
    categorytable.categoryCode 

,或者用左連接

SELECT 
    coalesce(COUNT(maintable.categoryCode),0) AS recordcount, 
    categorytable.categoryCode AS catCode, 
    categorytable.categoryname 
FROM 
    categorytable 
LEFT JOIN maintable ON categorytable.categoryCode = maintable.categoryCode 
GROUP BY 
    categorytable.categoryCode, 
    categorytable.categoryname 
ORDER BY 
    categorytable.categoryCode 
+0

+1。 Re第二個例子:你的其他'LEFT' ;-) – bernie

+1

該死的Ctrl + V!它不能讀取它必須第二次粘貼一個「左」? Buhhhh愚蠢的鍵盤。它何時會學習? – AlexanderMP