如果未通过左联接找到记录,如何将记录计数为零?

时间:2019-07-16 09:02:44

标签: mysql sql left-join

我正在尝试使用左连接获取计数为0的记录。我正在使用MySQL数据库。

门户表格:

SELECT * FROM portal;

    id  name
    -----------
    1   Barnet
    2   Brexley
    3   Balby

应用程序表:

id     portal_id    updated
-----------------------------
1         1        2011-08-20
2         1        2011-08-20
3         1        2011-08-21
4         2        2011-08-21
5         2        2011-08-20
6         2        2011-08-20
7         2        2011-08-21
8         2        2011-08-21

这是我的查询:

SELECT 
    portal.name, COALESCE(COUNT(application.id), 0) AS count
FROM
    portal
        LEFT JOIN
    application ON application.portal_id = portal.id
GROUP BY portal.name;

下面是输出SQL Fiddle

Name     Count
--------------
Balby      0
Barnet     3
Brexley    5

但是当我包含WHERE子句时,我没有得到计数为0的记录。

SELECT 
    portal.name, COALESCE(COUNT(application.id), 0) AS count
FROM
    portal
        LEFT JOIN
    application ON application.portal_id = portal.id
WHERE
    application.updated > '2011-08-20'
GROUP BY portal.name;

输出SQL Fiddle 2

Name     Count
--------------
Barnet     1
Brexley    3

3 个答案:

答案 0 :(得分:1)

根据@MadhurBhaiya的评论,请勿使用WHERE,而应将测试application.updated > '2011-08-20'置于JOIN条件下。

SELECT 
    portal.name, COUNT(COALESCE(application.id, 0) AS count
FROM
    portal
        INNER JOIN
    application ON (
        application.portal_id = portal.id
            AND
        application.updated > '2011-08-20'
    )
GROUP BY portal.name;

注意:我没有测试代码,也不太会说SQL。

答案 1 :(得分:0)

WHERE中的条件(即使它属于INNER JOIN也被视为LEFT JOIN,因此请您将日期条件放在left join的正下方,以过滤/限制该表中的数据仅

SELECT 
    portal.name, COALESCE(COUNT(application.id), 0) AS count
FROM portal
LEFT JOIN application ON application.portal_id = portal.id
    AND application.updated > '2011-08-20'
GROUP BY portal.name;

答案 2 :(得分:0)

申请条件应在on子句中。但是,我建议将查询编写为:

SELECT p.name, COUNT(a.id) AS count
FROM portal p LEFT JOIN
     application a
     ON a.portal_id = p.id AND
        a.updated > '2011-08-20'
GROUP BY p.name;

注意:

  • COUNT()不会返回NULL的值,因此COALESCE()是不必要的。
  • 使用表别名的缩写。
  • 您可能还希望按p.id进行排序,除非您知道名称是唯一的。