在JOIN期间从单个查找表联接多个表

时间:2018-09-06 01:13:07

标签: mysql pdo

我正在尝试从多个表输出多个列。通常,我将使用内部联接,因此我将知道查找表中id的值。

SELECT  people.*,                    
        category.name AS category_name,
FROM people 
INNER JOIN category ON people.category_id = category.id

但是我需要对具有相同行数据的同一查找表进行多次查找。

在以下情况下,我想知道什么人从事什么工作,他们的类别是什么以及通常的“默认”工作状态是什么。

但是我似乎无法对查询表执行两个INNER JOIN

我尝试过

SELECT  people.*,                    
        jobs.* 
        category.name AS category_name,

FROM people p

JOIN jobs AS j ON p.job_id = jobs.id
INNER JOIN category ON people.category_id = category.id

但是,恐怕我对自己的问题了解得不够多,无法弄清楚问谷歌什么。

有帮助吗?

+----+-------+--------+-------------+
| id | name  | job_id | category_id |
+----+-------+--------+-------------+
| 1  | Adam  | 1      | 1           |
+----+-------+--------+-------------+
| 2  | Beth  | 2      | 2           |
+----+-------+--------+-------------+
| 3  | Clint | 1      | 2           |
+----+-------+--------+-------------+

工作

+----+-------+-----------+
| id | name  | category  |
+----+-------+-----------+
| 1  | Cook  | 1         |
+----+-------+-----------+
| 2  | Nurse | 2         |
+----+-------+-----------+

类别

+----+-----------+
| id | name      |
+----+-----------+
| 1  | Full-Time |
+----+-----------+
| 2  | Part-Time |
+----+-----------+

我想要的结果

+----+-------+--------+----------+--------------+-------------+---------------+
| id | name  | job_id | job_name | job_category | category_id | category_name |
+----+-------+--------+----------+--------------+-------------+---------------+
| 1  | Adam  | 1      | Cook     | Full-Time    | 1           | Full-Time     |
+----+-------+--------+----------+--------------+-------------+---------------+
| 2  | Beth  | 2      | Nurse    | Part-Time    | 2           | Part-Time     |
+----+-------+--------+----------+--------------+-------------+---------------+
| 3  | Clint | 1      | Cook     | Full-Time    | 2           | Part-Time     |
+----+-------+--------+----------+--------------+-------------+---------------+

1 个答案:

答案 0 :(得分:1)

您只需要两次加入category表,一次用于人员类别,一次用于职位类别。该查询将执行您想要的操作:

SELECT p.name, p.job_id, j.name AS job_name, 
       c1.name AS job_category, p.category_id, c2.name AS category_name
FROM people p
JOIN jobs j ON j.id = p.job_id
JOIN category c1 ON c1.id = j.category
JOIN category c2 ON c2.id = p.category_id

输出:

name    job_id  job_name    job_category    category_id     category_name
Adam    1       Cook        Full-Time       1               Full-Time
Beth    2       Nurse       Part-Time       2               Part-Time
Clint   1       Cook        Full-Time       2               Part-Time

SQLFiddle Demo