简体   繁体   English

在mysql中左连接子查询的结果

[英]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):一般而言,如果您需要使用相同的子查询两次,您可以使用 CTE(公用表表达式):

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. CTE(上面查询的“with”部分)就像一个变量。 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 OP 似乎在 8.0 之前的 mysql 版本上,并且 db OP 不支持 CTE

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或者,您可以在 select 语句中重复子查询两次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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