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

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


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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2011/07/12/f2eb3e92197dcbbe7935464f2af8f52d.html



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