MySQL查询有两个连接

时间:2013-01-30 21:01:08

标签: mysql sql join

我有查询我需要在三个链接表上执行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 个答案:

答案 0 :(得分:7)

这是因为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

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

答案 1 :(得分:0)

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

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

答案 2 :(得分: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

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

答案 3 :(得分: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