109

我正在运行这个 SQL 查询:

SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM  wp_woocommerce_order_items
LEFT JOIN 
    (
        SELECT meta_value As Prenom
        FROM wp_postmeta
        WHERE meta_key = '_shipping_first_name'
    ) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE  wp_woocommerce_order_items.order_id =2198

我得到这个错误:

#1054 - 'on 子句'中的未知列'a.post_id'。

我认为我的代码很简单,但我做不到。我究竟做错了什么?

4

2 回答 2

184

您没有post_id在子查询中选择。您必须像这样在子查询中选择它:

SELECT wp_woocommerce_order_items.order_id As No_Commande
FROM  wp_woocommerce_order_items
LEFT JOIN 
    (
        SELECT meta_value As Prenom, post_id  -- <----- this
        FROM wp_postmeta
        WHERE meta_key = '_shipping_first_name'
    ) AS a
ON wp_woocommerce_order_items.order_id = a.post_id
WHERE  wp_woocommerce_order_items.order_id =2198 
于 2013-05-27T15:22:37.310 回答
23

我认识到答案有效并且已被接受,但有一种更简洁的方式来编写该查询。在 mysql 和 postgres 上测试。

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198 
于 2014-01-29T20:47:38.183 回答