我正在运行此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 clause'中的未知列'a.post_id'。
我认为我的代码非常简单,但我无法做到正确。我究竟做错了什么?
答案 0 :(得分:98)
您未在子查询中选择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
答案 1 :(得分:17)
我认识到答案有效且已经被接受但是有一种更清晰的方式来编写该查询。测试了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