2

我有查询需要在 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

有人帮忙吗?

4

4 回答 4

11

这是因为 mysql 的行为。左连接之后的内连接使左连接成为内连接。

SELECT areas.name AS aname, COUNT(consultants.id) AS cct 
FROM areas
    LEFT JOIN consAreas ON consAreas.area = areas.id 
    LEFT JOIN consultants ON consultants.id = consAreas.cons AND consultants.active = 1
WHERE 
    areas.areaID = $area 
GROUP BY areas.id 
ORDER BY areas.name

在这里你可以看到我只使用左连接,更重要的consultants.active是直接从左连接 ON 子句过滤状态。

于 2013-01-30T21:16:35.213 回答
0

你在这里想要的是一个LEFT JOIN(又名左外连接)。

只有当它在两个表中都有对应的行时, A JOIN(实际上是内部连接)才会选择由 JOIN 产生的行。如果只有左表有匹配的行,左连接将选择行,而不管右表是否匹配。

因此,在您加入顾问表时:

SELECT areas.name AS aname, COUNT(consAreas.area) AS cct 
FROM areas LEFT OUTER JOIN consAreas 
ON consAreas.area = areas.id 
LEFT JOIN consultants ON consultants.id = consAreas.cons
于 2013-01-30T21:11:47.853 回答
0

您需要执行LEFT JOIN并更正GROUP BY. 试试这个:

SELECT areas.name AS aname, COUNT(consultants.active) AS cct 
    FROM areas 
    LEFT JOIN consAreas 
      ON consAreas.area = areas.id 
    LEFT JOIN consultants 
      ON consultants.id = consAreas.cons
   WHERE areas.areaID = $area 
     AND consultants.active = 1
GROUP BY areas.name
ORDER BY areas.name

这将返回一个包含区域名称和活跃顾问数量的表格

于 2013-01-30T21:12:09.420 回答
0

试试这个:

SELECT areas.name AS aname, COUNT(consultants.id) AS cct 
    FROM areas LEFT OUTER JOIN consAreas 
      ON consAreas.areaID = areas.id 
    LEFT OUTER JOIN consultants ON consAreas.consultantID=consultants.id AND consultants.active = 1
   WHERE areas.areaID = $area 
     GROUP BY areas.id 
ORDER BY areas.name
于 2013-01-30T21:12:49.607 回答