我在表trades
中有两列引用另一个表auto_id
中的customers
列。
我想显示两个列中与该表中每个customers.customer_name
对应的客户名称auto_id
。
在表交易中,customer1_id
和customer2_id
都是引用表customers
中相同主键的外键,即auto_id
。
示例:
表customers
:
| auto_id | customer_name |
| 150 | jake |
| 159 | homer |
表trades
:
| customer1_id | customer2_id | status |
| 150 | 159 | traded |
| 150 | 160 | null |
| 152 | 240 | traded |
预期的结果(在选择或视图中):
| customer1_id | customer2_id | status |
| jake | homer | traded |
我真正想要实现的目标:显示jake与customer2_id
进行交易的所有交易,并在结果中显示customer2的真实姓名(如果可能,则显示auto_id
,但在至少它的真名。)
我只设法显示一个带有连接的customerX_id
列(不替换id,但在最终输出中将其添加到右侧),但我找不到兼顾两者的方法。
select p.customer1_id, p.customer2_id, b.auto_id, b.customer_name
from trades as p
inner join customers as b on b.auto_id = p.customer1_id;
哪个给出了
| customer1_id | customer2_id | status | auto_id | customer_name |
| 150 | 159 | traded | 150 | jake |
我只需要将本垒打显示在某个地方。
答案 0 :(得分:2)
如果您的问题是获得第二个客户的名称,那么您需要做的就是添加第二个联接:
select p.customer1_id, p.customer2_id, c1.auto_id, c1.customer_name, c2.auto_id, c2.customer_name
from trades as p
inner join customers as c1 on c1.auto_id = p.customer1_id
inner join customers as c2 on c2.auto_id = p.customer2_id