繁体   English   中英

SQL 查询与 2 个表的连接,并在第二个表中使用多个外键在结果中创建一组新的列

[英]SQL Query with join for 2 tables and create new set of columns in result with multiple foreign key in 2nd table

再会,

我正在尝试从 2 个表中获取新的查询结果列表。 下面是示例结构:

表格1

| id | name |
| 11  | Mic  |
| 22  | Jeff |
| 33  | Tom  |

而第二张桌子是这样的。 表2

| id | note | customerId1 | customerId2 | customerId3
| 1  | test | 11          | 11          | 22
| 2  | test |             | 33          | 

所以结果应该是这样的:

| id | note | customer1 | customer2 | customer3 |
| 1  | test | Mic       | Mic       | Tom       |
| 2  | test |           | Tom       |           |

到目前为止我尝试的是使用左连接,如下所示:

SELECT Table2.note, Table2.customerId1 as customer1, Table2.customerId2 as customer2,
       Table2.customerId13 as customer3
FROM Table2
    LEFT JOIN Table1 ON Table2.customerId1 = Table1.Id

但这还不够,这是我的要求。

我希望有人可以帮助解决这个问题。 谢谢你。

你可以试试下面的 - DEMO

SELECT t.id, note, t1.name as customer1, t2.name as customer2, 
t3.name as customer3
from table2 t
LEFT JOIN Table1 t1 ON t.customerId1 = t1.Id
LEFT JOIN Table1 t2 ON t.customerId2 = t2.Id
LEFT JOIN Table1 t3 ON t.customerId2 = t3.Id

您可以left join三倍:

select t2.id, t2.note, t11.name customer1, t12.name customer2, t13.name customer3
from table2 t2
left join table1 t11 on t11.id = t2.customerid1
left join table1 t12 on t12.id = t2.customerid2
left join table1 t13 on t13.id = t2.customerid3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM