简体   繁体   中英

Left join the result of subquery in mysql

I would like to do the following and it is not working. I would like to left join the result of a subquery.

select result1.id, result.name from (select cust.id as id, cust.name as name, ss.sold_date as soldDate, pp.product_name as productName from customers cust
left join sales ss on ss.customer_id = cust.id
left join products pp on pp.id = ss.product_id) as result
left join result as result1 on result.id = result1.id

When I do this, it says table 'result' does not exist. How do I left join the result alias?

As per your comment you're trying to join the subquery result with itself.

In this particular case it does not make any sense because you'll just get the same data twice. So, using the subquery once will work

select result1.id, result.name 
  from (select cust.id as id, cust.name as name, ss.sold_date as soldDate, pp.product_name as productName 
          from customers cust
          left join sales ss on ss.customer_id = cust.id
          left join products pp on pp.id = ss.product_id) as result
  left join result as result1 on result.id = result1.id

I general, if you need to use same sub-query twice, you may use a CTE (common-table-expression):

with sub_q as (select cust.id as id, cust.name as name, ss.sold_date as soldDate, pp.product_name as productName 
          from customers cust
          left join sales ss on ss.customer_id = cust.id
          left join products pp on pp.id = ss.product_id)

select *
  from sub_q res
  left join sub_q res1
    on res.id = res1.id

The CTE (the "with" part of the query above) is like a variable. In "usual" programming languages variable is being used to store values, whereas in query language it's job to store queries

UPD. The OP appeared to be on mysql version prior to 8.0 and the db OP is on doesn't support CTEs

So, here you may end up using views for example

First, a script to creaate a view

create view sub_q as select cust.id as id, cust.name as name, ss.sold_date as soldDate, pp.product_name as productName 
          from customers cust
          left join sales ss on ss.customer_id = cust.id
          left join products pp on pp.id = ss.product_id;

Second, run the query

select *
  from sub_q res
  left join sub_q res1
    on res.id = res1.id;

Alternatively you may repeat subquery twice in the select statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM