Let's say I have two tables:
TABLE A
MessageID | Message
1 | Hello
2 | Bonjouretc..
TABLE B
CommentID | MessageID | Comment
1 | 2 | This is a comment to someone saying Bonjour
2 | 2 | This is another comment to BonjourWhat I'm trying to开发者_开发百科 do is run one query that pulls all the records from Table A ("the messages") along with a count of all the comments for each message from Table B.
The result would be:
Hello - 0 comments Bonjour - 2 comments
I know this is probably some combination of using a join with a count(*), but I can't seem to hit on just the right syntax.
Any ideas?
For a message based approach:
SELECT message, count(commentID)
FROM tableA LEFT JOIN tableB ON tableA.messageID = tableB.messageID
GROUP BY message
You'll want a LEFT JOIN to include records in Table A that don't have any comments in Table B.
Give this a try:
SELECT a.MessageID, COUNT(*)
FROM TABLEA a
JOIN TABlEB b
ON b.MessageID = a.MessageID
GROUP BY a.MessageID
Just an addendum to what's already posted since, if you're using this for a scripting language, you'll likely need named columns for everything in the SELECT list:
SELECT tableA.messageID, message, count(commentID) AS commentCount
FROM tableA LEFT JOIN tableB ON tableA.messageID = tableB.messageID
GROUP BY message
Something like this:
SELECT MessageID, COUNT(CommentID)
FROM "TABLE B"
GROUP BY MessageID
If you need Message in addition to MessageID, you should be able to do something like this:
SELECT MessageID, MIN(Message), COUNT(CommentID)
FROM "TABLE A" LEFT JOIN "TABLE B" USING (MessageID)
GROUP BY MessageID
(Oracle syntax, probably same for MSSQL)
精彩评论