[翻译]  T-SQL Select and count from different table?

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


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.

我有一个包含字段(id)的表(Threads)。我想从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)

2 个解决方案

#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

#2


31  

Sure - something like this?

当然 - 这样的事情?

SELECT 
    t.ThreadID,
    (SELECT COUNT(*) FROM dbo.Posts p WHERE p.ThreadID = t.ThreadID)
FROM
    dbo.Threads t

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号