sql使用两个外键左连接并将它们合并到一行(mysql)

olmpazwi  于 2021-06-25  发布在  Mysql
关注(0)|答案(4)|浏览(288)

我有以下表格
订单:

id | address1 | address2 | state
1  | 2        | 4        | Delivered
2  | 7        | 1        | Payment

地址:

id | city
1  | New York 
2  | Paris   
4  | London 
7  | Berlin

现在我需要一个声明来获取这两个城市的订单状态。
例如,订单id 1应输出: Delivered | Paris | London 我尝试了以下陈述:

SELECT orders.state, address.city FROM orders
  LEFT JOIN address 
    ON orders.address1 = address.id OR orders.address2 = address.id;

它显然只输出一个地址城市,但我想要两个。
你知道这个声明应该是什么样子吗?

vlju58qv

vlju58qv1#

你可以做这个 self join :

select o.status, ad.city, ad1.city
from Orders o 
left join Address ad on ad.id = o.address1 
left join Address ad1 on ad1.id = o.address2;
fcwjkofz

fcwjkofz2#

如果希望表有别名,这将使其可读。

SELECT o1.state, a1.city, a2.city FROM orders o1
  LEFT JOIN address a1 
    ON o1.address1 = a1.id 
  LEFT JOIN address a2
    ON o1.address2 = a2.id 
    ;
yks3o0rb

yks3o0rb3#

我们需要达成这样一种理解,即我们必须处理两个不同的表,而不是一个表,因为我们希望从同一个表得到不同的结果集。另外,我们需要的是精确的数据,而不是额外的数据,因此选择了内部连接
解决方案:

SELECT O.ID,AD1,A.CITY City1,  o.AD2, b.City City2, STATE FROM ORDERS O
JOIN 
ADDRS A
ON O.AD1=A.ID
JOIN ADDRS b
on  O.AD2=b.ID

如果需要ddl和dml脚本:

create table orders
(id int , ad1 int, ad2 int,state varchar(20))

insert into orders values
(2,7,1,'Payment')

create table addrs(id int,city varchar(20))

insert into addrs values(1,'NY') 
insert into addrs values(2,'Paris')
insert into addrs values(4,'London')
insert into addrs values(7,'Berlin')

select * from orders
select * from addrs

希望这个答案更多地关注概念,而不是解决方案

7dl7o3gd

7dl7o3gd4#

试试这个

SELECT o.ID, (CASE WHEN o.address1 = a.id THEN a.city) as addy1, 
             (CASE WHEN o.address2 = a.id THEN a.city) as addy2 
FROM Orders as o LEFT JOIN Address as a WHERE ...

相关问题