一尘不染

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

sql

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

如何在SQL中完成?

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


阅读 185

收藏
2021-03-10

共1个答案

一尘不染

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
2021-03-10