简体   繁体   中英

SQL: How to select a count of multiple records from one table, based on records in a different table?

Let's say I have two tables:

TABLE A

MessageID | Message

1 | Hello
2 | Bonjour

etc..

TABLE B

CommentID | MessageID | Comment

1 | 2 | This is a comment to someone saying Bonjour
2 | 2 | This is another comment to Bonjour

What 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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM