具有元键和值的MySQL查询

时间:2014-09-28 23:57:46

标签: mysql sql join

我很难绕过这个问题找出一个干净的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
------------------------------- 

我需要包含没有_weight定义为关键字的产品,因此它会给我以下结果:

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

1 个答案:

答案 0 :(得分:1)

尝试使用外部联接:

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'

小提琴测试: http://sqlfiddle.com/#!2/dd3ad6/2/0

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

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'

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