JOIN中有三个表的零COUNT

时间:2015-02-05 16:42:16

标签: mysql join count

我有三张桌子;县,公墓和格雷夫斯。 Graves表中的Marked列是布尔值。查询结果应包括每个墓地中“标记”坟墓的数量,包括零数。

    County
-------------------------
|  CountyID  | Name      |
-------------------------|
|   351      | Lee       |
|   352      | Glascock  |
-------------------------


   Cemetery
--------------------------------------
| CEMID  |  CountyID  | Name          |
--------------------------------------|
|  1     |      352   | Smith Family  |
|  2     |      352   | Adams Family  |
|  3     |      352   | Jones Family  |
|  4     |      351   | Harris Family |
--------------------------------------

   Graves
--------------------------------------
|  ID | CEMID |     Name     | Marked |
--------------------------------------|
|  1  |   1   | John Smith   |   Y    |
|  2  |   1   | Mary Smith   |   N    |
|  3  |   1   | Frank Smith  |   Y    |
|  4  |   1   | Jane Smith   |   N    |
|  5  |   2   | John Adams   |   Y    |
|  6  |   2   | Ed Adams     |   N    |
|  7  |   3   | Susan Jones  |   N    |
--------------------------------------

   Query Result
----------------------------------
|  CEMID |     Name       | Count |
----------------------------------|
|  1     |  Smith Family  |  2    |
|  2     |  Adams Family  |  1    |
|  2     |  Jones Family  |  0    |
----------------------------------|

My current SELECT statement:

SELECT Cemetery.Name, Cemetery.CEMID, COUNT(Grave.Marked) AS Count
         FROM Cemetery
         JOIN County
         ON Cemetery.CountyID = County.CountyID
         JOIN Grave
         ON Cemetery.CEMID = Grave.CEMID
         WHERE CountyID = 352
         AND Grave.Marked = TRUE
         GROUP BY Cemetery.CEMID;

此声明返回结果,但不包括Jones Family墓地,因为标记计数为零。我知道“Grave.Marked = TRUE”在错误的地方,但我应该在哪里将Count计算为包括标记计数为零的墓地。

1 个答案:

答案 0 :(得分:0)

您想使用left join

SELECT c.Name, c.CEMID, COUNT(g.Marked) AS Count
FROM Cemetery c LEFT JOIN
     Grave g
     ON c.CEMID = g.CEMID AND g.Marked = TRUE
WHERE c.CountyID = 352
GROUP BY c.CEMID;

对查询的更改:

  • 不需要county表。您可以从cemetary获取ID。
  • join现在是left join
  • Marked上的条件已移至on子句而非where子句。
  • 使用表别名可以使查询更容易编写和阅读。