2011-08-30 75 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

相关问题