我有一个查询可以执行我需要做的所有事情,但是它很脆弱,而且确实非常复杂,我希望简化一下。我认为这很复杂,因为需要将行转换为元数据的列。
SELECT
O.order_item_id,
O.order_item_name,
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',
MAX(CASE WHEN OIM.meta_key = 'enrolment_id' THEN (
SELECT firstname FROM wp_enrolments E WHERE OIM.meta_value=E.id) END) as 'name',
MAX(CASE WHEN OIM.meta_key = 'enrolment_id' THEN (
SELECT surname FROM wp_enrolments E WHERE OIM.meta_value=E.id) END) as 'surname',
MAX(CASE WHEN OIM.meta_key = 'enrolment_Id' THEN (
SELECT UM.meta_value
FROM wp_usermeta UM, wp_enrolments E
WHERE UM.meta_key='_user_phone'
AND UM.user_id=E.memberid
AND E.memberid=OIM.meta_value
AND OIM.meta_key='enrolment_id' LIMIT 1) END) as 'phone',
MAX(CASE WHEN OIM.meta_key = 'enrolment_id' THEN (
SELECT U.user_email
FROM wp_users U, wp_enrolments E
WHERE U.id=E.memberid
AND E.memberid=OIM.meta_value
AND OIM.meta_key='enrolment_id' LIMIT 1) END) as 'email',
FROM wp_woocommerce_order_items O
INNER JOIN wp_woocommerce_order_itemmeta OIM ON O.order_item_id = OIM.order_item_id
GROUP BY O.order_item_id
答案 0 :(得分:0)
考虑所有子查询表的LEFT JOIN
,然后在CASE
语句中使用这些列。注意:如果没有数据,则未经测试,可能需要进行调整,但可以帮助您重构SQL查询。由于不同的联接字段( id 和 memberid ),需要两个 wp_enrolments 联接:
SELECT
O.order_item_id,
O.order_item_name,
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`,
MAX(CASE WHEN OIM.meta_key = 'enrolment_id' THEN idE.firstname END) as `name`,
MAX(CASE WHEN OIM.meta_key = 'enrolment_id' THEN idE.surname END) as `surname`,
MAX(CASE WHEN OIM.meta_key = 'enrolment_Id' AND UM.meta_key='_user_phone' THEN UM.meta_value END) as `phone`,
MAX(CASE WHEN OIM.meta_key = 'enrolment_id' THEN U.user_email END) as `email`
FROM wp_woocommerce_order_items O
INNER JOIN wp_woocommerce_order_itemmeta OIM
ON O.order_item_id = OIM.order_item_id
LEFT JOIN wp_enrolments idE
ON OIM.meta_value = idE.id
LEFT JOIN wp_enrolments memE
ON OIM.meta_value = memE.memberid
AND OIM.meta_key = 'enrolment_id'
LEFT JOIN wp_users U
ON U.id = memE.memberid
LEFT JOIN wp_usermeta UM
ON UM.user_id = memE.memberid
GROUP BY O.order_item_id,
O.order_item_name