2011-08-30 79 views
6

說,有兩個表:SQL:獲取一個表中的所有記錄和第二個表中的記錄數?

表A

messageID/Message     /More.. 
1  /This is the first message /Etc.. 
2  /This is the second message/Etc.. 
3  /This is the third message /Etc.. 

表B

commentID/messageID/Comment 
1  /2  /This is a comment to the second message 
2  /2  /This is another comment to the second message 
3  /3  /This is a comment to the third message 

表之間的系是MESSAGEID字段。

我想一個查詢產生的結果這樣的,其中I拉的所有字段進行表A的,以及意見從表B每個消息的數量的計數,像這樣:

messageID/Message     /More.../CommentCount 
1  /This is the first message/etc... /0 
2  /This is the second message/etc... /2 
3  /This is the third message/etc... /1 

我試過這樣的:

SELECT tableA.*, count(commentID) as commentcount 
FROM tableA LEFT JOIN tableB ON tableA.messageID = tableB.messageID GROUP BY messageID 

但它不起作用。有任何想法嗎?似乎應該可以在一個查詢中執行此操作。我正在使用MSSQL。謝謝你的幫助。

+2

你的查詢似乎是正確的。只需使用'COUNT(tableB.messageID)'和'GROUP BY tableA.messageID' –

回答

13

標量子查詢將工作:

SELECT tableA.* 
    ,(SELECT count(commentID) FROM tableB WHERE tableA.messageID = tableB.messageID) as commentcount 
FROM tableA 

像往常一樣,有很多方法對皮膚這隻貓,具有不同的性能特徵。

當使用GROUP BY,輸出中的所有列要麼必須在GROUP BY或聚合函數 - 即使是有MESSAGEID內的其他列沒有變化,他們仍然將需要在GROUP BY

+0

這正是我正在尋找的。謝謝! – PDD

2

嘗試此查詢:

SELECT a.*, b.msgCount 
    FROM tableA a LEFT JOIN 
    (SELECT messageID, COUNT(1) AS msgCount FROM tableB b GROUP BY messageID) b 
     ON a.messageID = b.messageID 
4

可以使用CTE爲相同。

;WITH CTE_MessageCount (MessageId, Count) 
AS 
(
SELECT MessageId, Count(*) FROM TableB GROUP BY MessageId 
) 

SELECT A.*, T.* 
FROM tableA A JOIN CTE_MessageCount T ON A.messageID = T.MessageID 
+0

謝謝Tushar,這也是一個很好的解決方案。我有「GROUP BY」,只是因爲我嘗試了各種不同的方法,但實際上並不需要它。 – PDD

+0

非常歡迎您!通用表表達式比嵌套SQL更受歡迎,因爲它們更高效。 – Tushar

相關問題