如何将一个表中的多个列连接到另一个查询表?

时间:2019-08-28 22:04:20

标签: sql sql-server

当一个表中的多个列引用另一个表时,我无法弄清楚如何将几个表连接在一起。

例如,我有一个“ document_statuses”表:

document_statuses table:
+-----------+-------------+
| status_id | status_name |
+-----------+-------------+
|         1 | RECEIVED    |
|         2 | MISSING     |
|         3 | NOT_NEEDED  |
+-----------+-------------+

现在在另一个表中,我正在跟踪多个文档的状态:

filings table:

+-----------+-------------+----------------+----------------+----------------+
| filing_id | filing_name | doc1_status_id | doc2_status_id | doc3_status_id |
+-----------+-------------+----------------+----------------+----------------+
|         1 | John        |              1 |              3 |              2 |
|         2 | Mikaela     |              2 |              3 |              2 |
|         3 | Sam         |              1 |              2 |              1 |
+-----------+-------------+----------------+----------------+----------------+

我该如何编写查询,为每列拉入status_name并产生以下结果:

+-------------+-------------+-------------+------------+
| Filing Name | Doc1 Status | Doc2 Status | Doc3Status |
+-------------+-------------+-------------+------------+
| John        | RECEIVED    | NOT_NEEDED  | MISSING    |
| Mikaela     | MISSING     | NOT_NEEDED  | MISSING    |
| Sam         | RECEIVED    | MISSING     | RECEIVED   |
+-------------+-------------+-------------+------------+

当从每行document_statuses中查找单个字段而不是多个字段时,我知道如何执行此操作。如果我在documents中只有一个列提到document_statuses,那么我会做一个简单的JOIN

SELECT filing_name, status_name
FROM documents d
LEFT JOIN document_statuses ds ON d.doc1_status = ds.status_id

但是当我需要多个时,该怎么办?

3 个答案:

答案 0 :(得分:2)

您需要使用相同的表别名为同一个表进行三次连接。

    SELECT filing_name, ds.status_name, ds1.status_name, 
    ds2.status_name FROM documents d
   LEFT JOIN document_statuses ds ON d.doc1_status
   LEFT JOIN document_statuses ds1 ON d.doc1_status
   LEFT JOIN document_statuses ds2 ON d.doc1_status

答案 1 :(得分:2)

您将需要多次连接状态表,然后对select子句中的列进行别名设置以使其成为所需的格式。请注意,您必须为join子句中的表加上别名,以便可以引用该语句的select子句中的列。

SELECT filing_name
, ds1.status_name AS 'Doc1 Status'
, ds2.status_name AS 'Doc2 Status'
, ds3.status_name AS 'Doc3 Status'
FROM documents d
LEFT JOIN document_statuses ds1 ON d.doc1_status = ds1.status_id
LEFT JOIN document_statuses ds2 ON d.doc2_status = ds2.status_id
LEFT JOIN document_statuses ds3 ON d.doc3_status = ds3.status_id

答案 2 :(得分:1)

您可以这样做:

select t1.filing_name, t2.status_name as doc1_status, t3.status_name as doc2_status, t4.status_name as doc3_status
from filings_table t1
inner join statuses_table t2 on t1.doc1_status_id = t2.status_id
inner join statuses_table t3 on t1.doc2_status_id = t3.status_id
inner join statuses_table t4 on t1.doc3_status_id = t4.status_id