MySQL多表联接为空

时间:2019-02-01 01:08:07

标签: mysql

我有以下两个表:

Codes
Code  key1   key2
1     a      hh
2     a   
3     a   
4     a   


Orders
key1   key2  val1
a      aa    foo
h      hh    bar

我想得到

Desired output
code   key1   key2  val1
1      a      hh    bar 
2      a
3      a
4      a

我已经尝试过使用订单的内部联接:

select 
      ordersa.key2, 
      code, 
      ordersb.date
   from 
      order ordersa
         right join codes
            on codes.key1 = orders.key1
         inner join orders ordersb
            on codes.key2 = ordersb.key2

但是这会删除key2列中的所有空数据,我得到:

code   key1   key2   val1
1      a      hh     bar 

关于如何实现这一目标的任何建议?

1 个答案:

答案 0 :(得分:2)

SELECT
  c.Code,
  c.key1,
  IFNULL(c.key2, '') key2,
  IFNULL(o.val1, '') val1,
FROM Codes c
LEFT JOIN Orders o ON c.key2 = o.key2