来自2个带有计数的表的SQL查询

时间:2012-10-03 14:39:52

标签: sql count group-by

我有2个表,表A和表B

A包含以下字段:

id(primary key), 
references_id

B也有字段:

id(primary_key) 
references_id. 

现在我收到了A的ID,我需要A.idcount(B.references_id) A.references_id

我如何在SQL查询中执行此操作?

3 个答案:

答案 0 :(得分:4)

使用LEFT JOIN,即使表references_id上没有B,它仍会显示。试试这样的事情,

SELECT  a.ID, COUNT(b.References_ID) totalCount
FROM    A LEFT JOIN B
            ON a.References_ID = b.References_ID
GROUP BY a.ID

答案 1 :(得分:1)

试试这个:

SELECT A.Id, COUNT(B.references_id)
FROM A
INNER JOIN B A.Reference_ID = B.References_ID
GROUP BY A.Id

答案 2 :(得分:1)

只是在那里抛出另一个选项,这次使用相关的子查询:

select a.id, (select count(*) from b where references_id = a.id) as ref_count
from a as a

奇怪的是,这有时可以提供比join and group by解决方案更高效的执行计划。我经常尝试两种方式。