使用元键和值的MySQL查询

使用元键和值的MySQL查询,mysql,sql,join,Mysql,Sql,Join,对于这个问题,我很难想出一个干净的mysql查询。我有两张桌子: ORDER ITEMS ORDER ITEM META ----------------- --------------------- ID Name ID Key Value ----------------- --------------------- 24 Produc

对于这个问题,我很难想出一个干净的mysql查询。我有两张桌子:

ORDER ITEMS                   ORDER ITEM META
-----------------             ---------------------
ID    Name                    ID    Key       Value   
-----------------             ---------------------
24    Product A               24    _qty      3
30    Product B               30    _qty      5
33    Product B               30    _weight   1000g
55    Product A               33    _qty      1
-----------------             33    _weight   500g
                              55    _qty      2
                              ---------------------
我运行了以下查询:

SELECT
    oi.ID,
    oi.Name,
    oim1.Value as Qty,
    oim2.Value as Weight

FROM
   `order_items` as oi
   INNER JOIN `order_item_meta` as oim1 ON oim1.ID = oi.ID
   INNER JOIN `order_item_meta` as oim2 ON oim2.ID = oi.ID

WHERE
   oim1.Key = '_qty' AND
   oim2.Key = 'weight'
但它只给了我

-------------------------------
ID   Name         Qty    Weight
-------------------------------
30   Product B    5      1000g
33   Product B    1      500g
------------------------------- 
我需要包括没有将_重量定义为关键的产品,这样它将给我以下结果:

-------------------------------
ID   Name         Qty    Weight
-------------------------------
24   Product A    3
30   Product B    5      1000g
33   Product B    1      500g
55   Product A    2
-------------------------------

尝试使用外部联接:

select oi.id, oi.name, oim1.value as qty, oim2.value as weight
  from order_items as oi
  join order_item_meta as oim1
    on oim1.id = oi.id
  left join order_item_meta as oim2
    on oim2.id = oi.id
   and oim2.key = '_weight'
 where oim1.key = '_qty'
小提琴测试:

如果存在订单没有数量的情况,您还必须对数量使用外部联接,如下所示:

select oi.id, oi.name, oim1.value as qty, oim2.value as weight
  from order_items as oi
  left join order_item_meta as oim1
    on oim1.id = oi.id
   and oim1.key = '_qty'
  left join order_item_meta as oim2
    on oim2.id = oi.id
   and oim2.key = '_weight'

但是,如果订单始终具有关联的数量(不一定是关联的权重),则应改用第一个查询、数量的内部联接和权重的外部联接。(这完全取决于你的情况)

我认为为了完整,需要让它一路加入,就像这样:@cha除非总是有数量,但有时只有重量,否则我们没有这个信息谢谢大家!该项目始终有一个关联的数量,因此我可以使用该项目的内部连接。但是,当可能不存在左连接时,最好知道使用左连接。@Rocky没问题,也只是为了澄清re:外部连接,order_项目和order_项目之间的左连接与order_项目和order_项目之间的右连接是一样的(只取决于每个表位于哪一侧,方向对于外部联接很重要,而对于内部联接则不重要。)“左外部联接”与“左联接”相同,“右外部联接”与“右联接”相同,当您指定方向时,这意味着您希望使用外部联接,因为这是唯一重要的时间方向。