简体   繁体   中英

Referencing a query result alias in a subquery

This is mostly a SQL syntax / SQL capability question. 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.

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 :

Derived tables cannot be correlated subqueries, or contain outer references or references to other tables of the same 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. 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.

The error in the 1st query is that a table alias (correlation name) can't be used as a table expression in a 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.)

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