Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
704 views
Welcome To Ask or Share your Answers For Others

1 Answer

Sure - something like this?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...