我有查询需要在 MySQL 中对三个链接表执行。我可以用嵌套查询以懒惰的方式做到这一点,但我无法弄清楚如何用单个查询来做到这一点。
表格是:
Area:-
: id (int)
: name (string)
Consultant:-
:id (int)
:active (1/0)
ConsArea:-
: areaID (int)
: consultantID (int)
我需要遍历所有区域(带有$area
变量),以便列出所有区域并针对每个区域指示“活动”顾问的数量......所以所有区域必须在其旁边列出一个值(可以是如果没有相关的活跃顾问,则为零)
查询的第一部分(无论顾问是否活跃)我可以这样做:
SELECT areas.name AS aname, COUNT(consAreas.areaID) AS cct
FROM areas LEFT OUTER JOIN consAreas
ON consAreas.areaID = areas.id
WHERE areas.areaID = $area
GROUP BY areas.id
ORDER BY areas.name
..但是当我想包括顾问处于活动状态的情况时,我无法计算出正确的加入。它仅列出活跃顾问数 > 0 的区域,而我需要所有区域。
SELECT areas.name AS aname, COUNT(consAreas.area) AS cct
FROM areas LEFT OUTER JOIN consAreas
ON consAreas.area = areas.id
**JOIN consultants ON consultants.id = consAreas.cons**
WHERE areas.areaID = $area
**AND consultants.active = 1**
GROUP BY areas.id
ORDER BY areas.name
有人帮忙吗?