T-SQL从不同的表中选择和计数?

时间:2011-07-12 16:09:02

标签: asp.net sql tsql

我有一个包含字段(Threads)的表(id)。我想从Threads中选择每一行,以及表Posts中的行数Posts.threadThreads.id相同的行数。

如何在SQL中完成?

(像这样的伪SQL:SELECT *, COUNT(* FROM Posts WHERE Posts.id=Threads.id) FROM Threads

2 个答案:

答案 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