如何在一个查询中选择woocommerce订单数据(wp_posts)并从同一列(wp_postmeta)添加多个值

时间:2019-02-05 11:42:39

标签: mysql wordpress select woocommerce post-meta

我正在寻找在一个查询中从同一列(wp_postmeta)中选择woocommerce订单数据(wp_posts)和多个值的最有效方法。我已经构建的作品行得通,但是我不确定这是否是实现此目的的最佳方法。

也许有人可以用一种更有效的方法来解决这个问题,因为随着很多订单的执行,它变得非常缓慢:第一个示例20秒以上,第二个示例60秒以上)。

我简化了这个示例,因为我现在每个订单获得8对不同的meta_key和meta_value对。

感谢您的帮助!

wp_postmeta的数据库结构如下:

meta_id | post_id | meta_key | meta_value

示例数据如下:

1 | 2 | _order_currency | EUR
2 | 2 | _billing_email | mail@mail.com
3 | 2 | _payment_method | paypal

到目前为止,我最好的解决方案:

SELECT
    p.ID,
    p.post_date,
    p.post_status,
    p.post_type,
    max( CASE WHEN pm.meta_key = '_order_currency' and p.ID = pm.post_id THEN pm.meta_value END ) as order_currency,
    max( CASE WHEN pm.meta_key = '_billing_email' and p.ID = pm.post_id THEN pm.meta_value END ) as billing_email,
    max( CASE WHEN pm.meta_key = '_payment_method' and p.ID = pm.post_id THEN pm.meta_value END ) as payment_method,
FROM
    wp_posts p 
JOIN 
    wp_postmeta pm 
        ON p.ID = pm.post_id
WHERE
    p.post_type = 'shop_order' 
AND
    p.post_status = 'wc-completed'
GROUP BY
    p.ID

我构建的另一个示例也可以运行,但速度较慢:

SELECT
    p.ID,
    p.post_date,
    p.post_status,
    p.post_type,
    pm1.meta_value as order_currency,
    pm2.meta_value as billing_email,
    pm3.meta_value as payment_method
FROM
    wp_posts p 
JOIN wp_postmeta pm ON p.ID = pm.post_id
LEFT JOIN wp_postmeta AS pm1 AND pm1.post_id = p.ID AND pm1.meta_key = '_order_currency'
LEFT JOIN wp_postmeta AS pm2 AND pm2.post_id = p.ID AND pm2.meta_key = '_billing_email'
LEFT JOIN wp_postmeta AS pm3 AND pm3.post_id = p.ID AND pm3.meta_key = '_payment_method'

WHERE
    p.post_type = 'shop_order' 
AND
    p.ID = pm.post_id
AND
    p.post_status = 'wc-completed'            
GROUP BY
    p.ID

0 个答案:

没有答案