带有2个外键的SQL LEFT-JOIN并将它们合并为一行(MySQL)

时间:2018-05-08 09:58:56

标签: mysql sql join foreign-keys left-join

我有以下表格

订单:

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;

显然只输出一个地址城市,但我想要两者。

知道声明应该是什么样的吗?

4 个答案:

答案 0 :(得分:1)

您可以执行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;

答案 1 :(得分:1)

您希望为表添加别名,这使其可读。

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 
    ;

答案 2 :(得分:0)

试试这个

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 ...

答案 3 :(得分:0)

我们需要达到这样的理解:我们必须处理2个不同的表而不是1个,因为我们希望从同一个表中获得不同的结果集。 我们也想要确切的数据,而不是额外的数据,因此选择内部连接

解决方案:

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

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