使用计数连接两个表

时间:2010-05-03 22:48:29

标签: sql

我有两个表定义如下:

EMAILS
ID       SUBJECT   BODY
1        Test1     blah blah
2        Test2     blah blah blah
3        Test3     more blah

ATTACHMENTS
ID   EMAIL_ID    ATTACHMENT NAME
1    2           TEST.DOC
2    2           TEST.XLS

我正在尝试执行选择以获取所有电子邮件以及EMAILS表中每行的多少附件(如果有)的计数 - 最好是在单个查询中,结果类似于:

EMAIL_ID    SUBJECT   NUM_ATTACHMENTS      BODY
    1       Test1     0                    blah blah
    2       Test2     2                    blah blah blah
    3       Test3     0                    more blah

除了“正确的方法”之外,我已经尝试了一切,如果有人有几分钟的时间帮助我创建正确的SQL来构建它,我将非常感激。感谢。

3 个答案:

答案 0 :(得分:3)

我喜欢brydgesk's solution,但在可能的情况下不希望使用子查询 当给定电子邮件没有附件时,此查询将显示0.

SELECT
    a.email_id,
    e.subject,
    e.body,
    COALESCE(count(a.id),0) AS NUM_ATTACHMENTS
FROM
    emails e
    LEFT OUTER JOIN attachments a
    ON e.id = a.email_id
GROUP BY 
    a.email_id, e.subject, e.body

答案 1 :(得分:0)

你尝试过这样的事吗? (另)

SELECT
    e.id,
    e.subject,
    count(*),
    e.body
FROM
    (SELECT *
    FROM emails e
    JOIN attachments a
    ON e.id = a.email_id)
GROUP BY e.id, e.subject, e.body

答案 2 :(得分:0)

您可以在SELECT子句中将其作为一个简单的子查询执行:

Select E.ID As EMAIL_ID
    , E.SUBJECT
    , ( Select Count(*) 
        From ATTACHMENTS As A
        Where A.EMAIL_ID = E.ID ) As NUM_ATTACHMENTS
    , E.BODY
From EMAILS As E