Referencing a query result alias in a subquery

£可爱£侵袭症+ 提交于 2020-04-30 08:26:06

问题


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
);

回答1:


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.




回答2:


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)



回答3:


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.)



来源:https://stackoverflow.com/questions/49177219/referencing-a-query-result-alias-in-a-subquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!