1

我有两个要查询的表,但我只能获得所需信息的一半。这两个表是:

客户技能新:

+----+-----------+------------+----------+-------------+
| 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 |
+----+-----------+------------+----------+-------------+

工作部门:

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

工作部门表实际上在一列(名称)中包含工作部门和工作类型。job_sector id 将两者联系起来(即 brokerage 是会计和金融的子标题 - job_sector_id = id)。

在 client_skills_new 表中,job_sector 和 job_type 下存储的数字与 job_sectors 的 id 列相关。我要做的是编写一个查询,它将两者结合起来,为我提供与 client_skills_new 中的 job_sector 和 job_type 整数相关的 job_sectors 表中的文本值。

到目前为止,我有一个查询如下:

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   |
+----+--------------------------+-----------+----------+
4

2 回答 2

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' ;
于 2013-06-27T15:56:34.007 回答
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';
于 2013-06-27T15:18:45.193 回答