简体   繁体   English

在子查询中引用查询结果别名

[英]Referencing a query result alias in a subquery

This is mostly a SQL syntax / SQL capability question.这主要是一个 SQL 语法/SQL 功能问题。 Why does the following query NOT work:为什么以下查询不起作用:

SELECT * from 
(
    select m.*, p.type,
    from multipliers m
    inner join pushes p
    on m.push_id = p.id
    where p.type = 'CONSTANT'
) AS res1 where res1.push_id = ( 
    select max(push_id) from res1
);

when the following completes without issue:当以下内容毫无问题地完成时:

SELECT * from 
(
    select m.*, p.type,
    from multipliers m
    inner join pushes p
    on m.push_id = p.id
    where p.type = 'CONSTANT'
) AS res1 where res1.push_id = ( 
    select max(push_id) from    
        (
            select m.push_id
            from multipliers m
            inner join pushes p
            on m.push_id = p.id
            where p.type = 'CONSTANT'
        ) AS res2
);

The first query doesn't work because the selected column doesn't exist.第一个查询不起作用,因为所选列不存在。 At least if you want to reuse it, it should be res.push_id , anyway it's better to use CTE as Jarlh said in his comment.至少如果你想重用它,它应该是res.push_id ,无论如何最好使用 CTE,正如 Jarlh 在他的评论中所说的那样。

WITH
 myCte AS (  select m.*, p.type,
           from multipliers m
          inner join pushes p
         on m.push_id = p.id
         where p.type = 'CONSTANT')
 SELECT * FROM myCte
 WHERE myCte.push_id = (SELECT MAX(push_id) FROM myCte)

Per the MySQL 5.7 documentation : 根据 MySQL 5.7 文档

Derived tables cannot be correlated subqueries, or contain outer references or references to other tables of the same SELECT.派生表不能是相关子查询,也不能包含外部引用或对同一 SELECT 的其他表的引用。

In other words, you can't reference a derived table in a subquery.换句话说,您不能在子查询中引用派生表。 The documentation doesn't state this, but it likely acts this way because of an OOO issue since the derived table isn't necessarily processed before the subquery.该文档没有说明这一点,但由于 OOO 问题,它可能会以这种方式运行,因为派生表不一定在子查询之前处理。 In MySQL 8.0 you will be able to use a Common Table Expression or CTE , which basically lets you define a reusable derived table before your query, but until then use your second approach.在 MySQL 8.0 中,您将能够使用Common Table Expression 或 CTE ,它基本上允许您在查询之前定义一个可重用的派生表,但在此之前使用您的第二种方法。

The error in the 1st query is that a table alias (correlation name) can't be used as a table expression in a FROM.第一个查询中的错误是表别名(相关名称)不能用作 FROM 中的表表达式。

A table alias with a dot & column identifies a column of a table.带有点 & 列的表别名标识表的列。 (In the predicate logic or relational calculus sense a table alias is a subrow-valued variable.) (在谓词逻辑或关系演算意义上,表别名是子行值变量。)

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

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