如何访问MySQL中的内部别名?

时间:2013-06-14 07:38:39

标签: mysql join union alias

我的存储过程需要这个条件,我可以以任何方式访问内部级别从其上下文之外声明的别名

这适用: -

SELECT Count(*)
FROM   (SELECT id
        FROM   postdata
        WHERE  id IN ( 4, 5, 6 )
        UNION
        SELECT id
        FROM   (SELECT id,
                       date_completed
                FROM   postdata
                WHERE  id IN ( 1, 2, 3 ))a
        WHERE  a.date_completed in  ( "2012-1-10", "2012-10-02" ) )b  

是否有可能使这项工作

SELECT Count(*)
FROM   (SELECT id
        FROM   postdata
        WHERE  id IN ( 4, 5, 6 )
        UNION
        SELECT id
        FROM   (SELECT id,
                       date_completed
                FROM   postdata
                WHERE  id IN ( 1, 2, 3 ))a)b
WHERE  a.date_completed IN ( "2012-1-10", "2012-10-02" )  

1 个答案:

答案 0 :(得分:1)

AFAIK,无法访问内部别名a

您必须在内部查询中添加判别式:

SELECT Count(*)
FROM   (SELECT 'a' AS discriminant,
               id
        FROM   postdata
        WHERE  id IN ( 4, 5, 6 )
        UNION
        SELECT 'b' AS discriminant,
               id
        FROM   (SELECT id,
                       date_completed
                FROM   postdata
                WHERE  id IN ( 1, 2, 3 ))a)b
WHERE  b.discriminant= 'a'
        OR ( b.discriminant= 'b'
             AND b.id IN ( 1, 2 ) )  

请参阅this fiddle