我有三张桌子;县,公墓和格雷夫斯。 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计算为包括标记计数为零的墓地。
答案 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
子句。