SQL LEFT JOIN子查询别名

我正在运行这个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'。

我认为我的代码非常简单,但是我不能说得对。 我究竟做错了什么?

您没有在子查询中selectpost_id 。 你必须像这样在子查询中select它:

 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 

我意识到答案是有效的,并且已经被接受,但是写出这个查询有一个更简洁的方法。 在mysql和postgres上testing。

 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