MySQL多次左连接问题

时间:2013-06-27 15:17:10

标签: mysql sql join left-join

我正在尝试查询两个表,而且我只能获得所需信息的一半。这两个表是:

client_skills_new:

+----+-----------+------------+----------+-------------+
| id | client_id | job_sector | job_type | job_name    |
+----+-----------+------------+----------+-------------+
| 79 | 24        | 3          | 39       | Accountant  |
+----+-----------+------------+----------+-------------+
| 80 | 25        | 3          | 115      | Broker      |
+----+-----------+------------+----------+-------------+
| 81 | 24        | 5          | 241      | Shop Worker |
+----+-----------+------------+----------+-------------+

job_sectors:

+-----+--------------------------+---------------+
| id  | name                     | job_sector_id |
+-----+--------------------------+---------------+
| 3   | Accounting & Finance     | 0             |
+-----+--------------------------+---------------+
| 115 | Brokerage                | 3             |
+-----+--------------------------+---------------+
| 22  | Sales & Retail           | 0             |
+-----+--------------------------+---------------+

作业扇区表实际上包含一列(名称)中的作业扇区和作业类型。 job_sector id链接两者(即经纪是会计和财务的副标题 - job_sector_id = id)。

在client_skills_new表中,job_sector和job_type下存储的数字与job_sectors的id列相关。我想要做的是编写一个查询,它将连接两者,以便在job_sectors表中提供与client_sector和job_type整数相关的文本值。

到目前为止,我的查询如下:

SELECT client_skills_new.job_sector, job_sectors.id, job_sectors.name 
FROM job_sectors
LEFT JOIN client_skills_new 
ON client_skills_new.job_sector = job_sectors.id
WHERE client_id='$client_id';

由此,我得到如下结果:

+------------+----+--------------------------+
| job_sector | id | name                     |
+------------+----+--------------------------+
| 3          | 3  | Accounting & Finance     |
+------------+----+--------------------------+
| 22         | 22 | Sales & Retail           |
+------------+----+--------------------------+

从我的顶级表中给出了24的id给了我大约一半我需要的东西。我希望查询还包括与job_type对应的文本名称。我不太确定我需要添加什么才能完成查询。我尝试了第二次左连接,但这仍然是错误的。

我正在寻找的输出,给定client_skills_new中的每个id,如下所示:

+----+--------------------------+-----------+----------+
| id | job_sector               | job_type  | job_name |
+----+--------------------------+-----------+----------+
| 80 | Accounting & Finance     | Brokerage | Broker   |
+----+--------------------------+-----------+----------+

2 个答案:

答案 0 :(得分:1)

是的,您需要2 LEFT个加入,但相反:

SELECT c.id, 
       js.name AS job_sector, 
       jt.name AS job_type,
       c.job_name  
FROM client_skills_new AS c
  LEFT JOIN job_sectors AS js
    ON c.job_sector = js.id
  LEFT JOIN job_sectors AS jt
    ON c.job_type = jt.id
WHERE c.client_id='$client_id' ;

答案 1 :(得分:0)

问题是where子句。它正在“撤消”left outer join,因为当没有匹配时,一个表中的值为NULL。

修复方法是将逻辑移到on子句:

SELECT client_skills_new.job_sector, job_sectors.id, job_sectors.name
FROM job_sectors LEFT JOIN
     client_skills_new
     ON client_skills_new.job_sector = job_sectors.id and
        client_id='$client_id';