T-SQL从不同的表中选择并计数吗? [英] T-SQL Select and count from different table?
本文介绍了T-SQL从不同的表中选择并计数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个表( Threads
),其中包含一个字段( id
).我想从 Threads
中选择每一行,以及表 Posts
中的行数,其中字段 Posts.thread
是与 Threads.id
相同.
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
.
如何在SQL中完成此操作?
How can this be done in SQL?
(类似于这种伪SQL: SELECT *,COUNT(* FROM Posts WHERE Posts.id = Threads.id)FROM Threads
)
(Something like this pseudo-SQL: SELECT *, COUNT(* FROM Posts WHERE Posts.id=Threads.id) FROM Threads
)
推荐答案
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
这篇关于T-SQL从不同的表中选择并计数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文