Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL LEFT JOIN Subquery Alias

I'm running 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 'on clause'.

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

like image 564
CharleyXIV Avatar asked May 27 '13 15:05

CharleyXIV


People also ask

Can we use alias in left join?

Rather than using the table names, you may also use table alias as specifying the tables in the LEFT OUTER JOIN query. LEFT JOIN sto_orders ORDs ON EMPs.id=ORDs. emp_id; The same result is retrieved as in case of the first example.

Can we use subquery in left join?

Move the 'Reserve' table named in the subquery to the FROM clause and join it to 'Customers' using LEFT JOIN. The WHERE clause compares the customer_id column to the ids returned from the subquery. Hence convert the IN expression to an explicit direct comparison between id columns of two tables in the FROM clause.

Can we give alias to subquery in SQL?

An SQL alias is useful for simplifying your queries and making the query and its result more readable. This article explains why and how you can use aliases in your SQL queries. You can temporarily rename a table or a column by giving it another name. This is known as an SQL alias.

Can you use a subquery with a join?

A subquery can be used with JOIN operation. In the example below, the subquery actually returns a temporary table which is handled by database server in memory. The temporary table from the subquery is given an alias so that we can refer to it in the outer select statement.


2 Answers

You didn't select post_id in the subquery. You have to select it in the subquery like this:

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  
like image 174
Mahmoud Gamal Avatar answered Oct 15 '22 01:10

Mahmoud Gamal


I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. 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  
like image 42
EJay Avatar answered Oct 15 '22 00:10

EJay