[英]T-SQL Select and count from different table?
I have a table ( Threads
) containing a field ( id
).我有一个包含字段( id
)的表( Threads
)。 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
.我想 select 来自Threads
的每一行,以及Posts
表中字段Posts.thread
与Threads.id
相同的行数。
How can this be done in SQL?如何在 SQL 中做到这一点?
(Something like this pseudo-SQL: SELECT *, COUNT(* FROM Posts WHERE Posts.id=Threads.id) FROM Threads
) (类似这样的伪 SQL: SELECT *, COUNT(* FROM Posts WHERE Posts.id=Threads.id) FROM Threads
)
Sure - something like this?当然 - 像这样的东西?
SELECT
t.ThreadID,
(SELECT COUNT(*) FROM dbo.Posts p WHERE p.ThreadID = t.ThreadID)
FROM
dbo.Threads t
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.