从1个左连接中获得2个结果

时间:2013-01-24 16:12:59

标签: mysql

我有一张包含订单的表格。每个订单都有一个发件人和一个收件人。发件人和收件人都在customers表中。每个客户可能在某个时间成为发件人或收件人,因此我无权将其拆分为发件人和收件人表。

我现在停留在构建(在一个查询中)一个JOIN,它将为我提供两个客户(一个作为发件人,一个作为接收者),我可以认为是“正确”的客户。

我可以制作一个标准的LEFT JOIN,

SELECT o.date,c.last_name,c.first_name,c.company,c.email
FROM orders o 
LEFT JOIN customers c ON ( o.sender = c.id )
WHERE o.id = 2";

但这只会告诉我发件人的信息。我可以将o.sender更改为o.receiver,但这只会让我获得接收者的信息。

如何同时获得两者并区分发送者和接收者中的哪一个?

提前致谢,

2 个答案:

答案 0 :(得分:1)

您可以在联接的ON子句中使用OR:

SELECT o.date, c.last_name, c.first_name, c.company, c.email,
       case when o.sender=c.id then 'Sender'
            when o.receiver=c.id then 'Receiver' end as kind_of_customer
FROM orders o 
      LEFT JOIN customers c ON o.sender = c.id or o.receiver = c.id
WHERE o.id = 2;

并使用案例当您可以区分它是发件人还是接收者时。

答案 1 :(得分:0)

您可以两次加入customer表。一旦返回sender,另一个将返回receiver

SELECT o.date,
  c1.last_name,
  c1.first_name,
  c1.company,
  c1.email,
  c2.last_name,
  c2.first_name,
  c2.company,
  c2.email
FROM orders o 
LEFT JOIN customers c1
  ON o.sender = c1.id
LEFT JOIN customers c2
  ON o.receiver = c2.id
WHERE o.id = 2";

如果您想使用更多描述性别名,那么您可以使用:

SELECT o.date,
  sender.last_name,
  sender.first_name,
  sender.company,
  sender.email,
  receiver.last_name,
  receiver.first_name,
  receiver.company,
  receiver.email
FROM orders o 
LEFT JOIN customers sender
  ON o.sender = sender.id
LEFT JOIN customers receiver
  ON o.receiver = receiver.id
WHERE o.id = 2";