说,有两个表: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。谢谢你的帮助。
你的查询似乎是正确的。只需使用'COUNT(tableB.messageID)'和'GROUP BY tableA.messageID' –