我有一个包含字段(Threads
)的表(id
)。我想从Threads
中选择每一行,以及表Posts
中的行数Posts.thread
与Threads.id
相同的行数。
如何在SQL中完成?
(像这样的伪SQL:SELECT *, COUNT(* FROM Posts WHERE Posts.id=Threads.id) FROM Threads
)
答案 0 :(得分:31)
当然 - 这样的事情?
SELECT
t.ThreadID,
(SELECT COUNT(*) FROM dbo.Posts p WHERE p.ThreadID = t.ThreadID)
FROM
dbo.Threads t
答案 1 :(得分:12)
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