sql选择计数

时间:2010-12-02 01:03:57

标签: sql tsql

我有两个表:呼叫和附件,我想显示呼叫表中的所有内容,但是还要显示呼叫是否有附件, - 通过确定是否存在带有call_id的附件记录。也许有附件,也许没有附件。

调用
CALL_ID
标题
描述

附件
attach_id
attach_name
call_id

如果我写:

select call_id, title, description from calls

给我一​​个所有电话的清单......

我如何还包括此通话记录是否有附件?

谢谢,

2 个答案:

答案 0 :(得分:3)

您可以使用外部联接来完成此任务:

SELECT c.call_id, title, description, attach_name
FROM calls c
LEFT OUTER JOIN attachments a ON c.call_id = a.call_id

如果没有找到附件,上面将显示(NULL)attach_name。如果未找到attach_name,则可以使用ISNULL()提供默认值,例如:

SELECT c.call_id, title, description, 
    ISNULL(attach_name, '(No attachment)') as attach_name
FROM calls c
LEFT OUTER JOIN attachments a ON c.call_id = a.call_id

答案 1 :(得分:1)

select a.call_id, a.title, a.description, count(b.attach_id)
from calls a, attachments b
where a.call_id = b.call_id
group by a.call_id, a.title, a.description
union all
select distinct a.call_id, a.title, a.description, 0
from calls a, attachments b
where not exists (select call_id from calls c where c.call_id = a.call_id)

这将为每个具有相同标题和说明的电话提供附件计数