元键:返回NULL的值字段

时间:2019-03-30 18:07:57

标签: mysql sql

我有一个围绕数据库中meta_key和meta_value字段的查询。差不多了,但是当我添加INNER JOIN wp_enrolments时,“类”和“费用类型”现在返回NULL。就像它与INNER JOIN wp_woocommerce_order_itemmeta行冲突。

wp_woocommerce_order_itemmeta的结构是

  • id
  • meta_key
  • meta_value

wp_enrolments表的结构为:

  • id
  • 名字

如果您能看一下我的语法并发现任何错误,我将不胜感激。

SELECT 
  O.order_item_id, O.order_item_name,
  E.firstname,
  MAX(CASE WHEN OIM.meta_key = 'class' THEN OIM.meta_value END) AS 'class',
  MAX(CASE WHEN OIM.meta_key = 'fee-type' THEN OIM.meta_value END) AS 'fees'
FROM wp_woocommerce_order_items O
INNER JOIN wp_woocommerce_order_itemmeta OIM ON O.order_item_id = OIM.order_item_id
INNER JOIN wp_enrolments E ON E.id = OIM.meta_value AND OIM.meta_key = 'enrolment_id'
GROUP BY O.order_item_id

1 个答案:

答案 0 :(得分:0)

也许您需要一个LEFT JOIN。另外,修复GROUP BY以匹配SELECT,并且不要对列别名使用单引号:

SELECT O.order_item_id, O.order_item_name, E.firstname,
       MAX(CASE WHEN OIM.meta_key = 'class' THEN OIM.meta_value END) AS class,
       MAX(CASE WHEN OIM.meta_key = 'fee-type' THEN OIM.meta_value END) AS fees
FROM wp_woocommerce_order_items O JOIN
     wp_woocommerce_order_itemmeta OIM
     ON O.order_item_id = OIM.order_item_id LEFT JOIN
     wp_enrolments E
     ON E.id = OIM.meta_value AND
        OIM.meta_key = 'enrolment_id'
GROUP BY O.order_item_id, O.order_item_name, E.firstname;