SQL LEFT JOIN Subquery Alias

I am using this SQL query:

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 

And I get this error:

# 1054 - Unknown column "a.post_id" in the "on" section.

I think my code is pretty simple, but I can't do it right. What am I doing wrong?

+42
sql left-join subquery
May 27 '13 at 15:21
source share
2 answers

You did not select post_id in the subquery. You should select it in the subquery as follows:

 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 
+71
May 27 '13 at 15:22
source share
— -

I understand that the answer works and has been accepted, but there is a much cleaner way to write this request. Tested on mysql and 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 
+14
Jan 29 '14 at 20:47
source share



All Articles