SQL Query,如何从两个表

时间:2017-01-19 04:34:11

标签: sql sql-server

表1

ID (unqiue), Name, Address

表2

RecordId, ID (key of table 1),  Child name

在一个查询中,我想检索表1的所有行,其中一个附加列将是ID中表2中所有记录的计数(即表1中每个ID的子项数)。无法弄清楚如何格式化查询以检索此数据。

3 个答案:

答案 0 :(得分:2)

只需加入并申请点数

select T1.*, COUNT(T2.RECORDID)AS T2COUNT from Table1 T1
INNER JOIN TABLE2 T2 ON T1.ID= T2.ID
--LEFT JOIN  TABLE2 T2 ON T1.ID= T2.ID  --if you need 0 child records (from commets by @Cha)
GROUP BY T1.ID  , T1.Name, T1.Address

答案 1 :(得分:1)

这样做的正确方法是使用OUTER JOIN:

SELECT a.ID, a.Name, a.Address, b.cnt
FROM Table1 a
LEFT OUTER JOIN
(SELECT ID, count(*) cnt from Table2 GROUP BY ID) b
ON a.ID = b.ID

错误的方法是借助相关的子查询:

SELECT a.ID, a.Name, a.Address, 
(SELECT count(*) FROM Table2 b WHERE b.ID = a.ID) as cnt
FROM Table1 a

Here是关于相关子查询与OUTER JOIN的讨论,如果您有兴趣

答案 2 :(得分:0)

按table1字段分组并计算table2中的总记录数: 这里是table1的T1别名和table2的T2别名。

select T1.ID, T1.Name, T1.Address, count(T2.ID) as total_records
from table1 as T1
left outer join table2 as T2 on T2.ID=T1.ID
group by T1.ID, T1.Name, T1.Address