T-SQL Select and count from different table?

I have a table (Threads) containing a field (id). I would like to select every row from Threads, as well as the number of rows in the table Posts where the field Posts.thread is the same as Threads.id.

How can this be done in SQL?

(Something like this pseudo-SQL: SELECT *, COUNT(* FROM Posts WHERE Posts.id=Threads.id) FROM Threads)

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Sure – something like this?

SELECT 
    t.ThreadID,
    (SELECT COUNT(*) FROM dbo.Posts p WHERE p.ThreadID = t.ThreadID)
FROM
    dbo.Threads t

Method 2

SELECT t.id, COUNT(p.thread)
FROM Threads AS t
    LEFT OUTER JOIN Posts AS p
        ON t.id = p.thread
GROUP BY t.id


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x