引用在 SELECT 中创建的自定义列



我想引用上面创建的列简写名称,以大大简化DATE_DIFF行以提高可读性,但不确定是否允许这样做。


像下面的代码一样的东西可能吗?请注意,DATE_DIFF的输入是在前面的 2 行中启动的。

SELECT DISTINCT
    Stuff ,
    DATE_FORMAT(FROM_UNIXTIME(date1), '%Y-%d-%m') as Date_Start ,
    DATE_FORMAT(FROM_UNIXTIME(date2), '%Y-%d-%m') as Date_End  ,
    DATE_DIFF( 'day' , Date_Start , Date_End) + 1 as Date_Delta ,    `<-- HERE
    More_Stuff 
FROM T1
LEFT JOIN T2
    ON Stuff = More_Stuff
LEFT JOIN T3
    ON More_Stuff = Other_Stuff

我希望避免将Date_StartDate_End的完整查询嵌套在DATE_DIFF内或使用另一个Join。如果这是无法完成的事情,那么可以将问题转换为此类事情的最佳实践是什么,为什么?

你要么看:

SELECT
    Stuff
    , Date_Start
    , Date_End
    , DATE_DIFF( 'day' , Date_Start , Date_End) + 1 as Date_Delta
    , More_Stuff
FROM
    (
        SELECT DISTINCT
            Stuff ,
            DATE_FORMAT(FROM_UNIXTIME(date1), '%Y-%d-%m') as Date_Start ,
            DATE_FORMAT(FROM_UNIXTIME(date2), '%Y-%d-%m') as Date_End  ,
            DATE_DIFF( 'day' , Date_Start , Date_End) + 1 as Date_Delta ,
            More_Stuff 
        FROM T1
        LEFT JOIN T2
            ON Stuff = More_Stuff
        LEFT JOIN T3
            ON More_Stuff = Other_Stuff
    ) as Q

或:

SELECT DISTINCT
    Stuff ,
    DATE_FORMAT(FROM_UNIXTIME(date1), '%Y-%d-%m') as Date_Start ,
    DATE_FORMAT(FROM_UNIXTIME(date2), '%Y-%d-%m') as Date_End  ,
    DATE_DIFF( 'day' , DATE_FORMAT(FROM_UNIXTIME(date1), '%Y-%d-%m') , DATE_FORMAT(FROM_UNIXTIME(date2), '%Y-%d-%m')) + 1 as Date_Delta ,
    More_Stuff 
FROM T1
LEFT JOIN T2
    ON Stuff = More_Stuff
LEFT JOIN T3
    ON More_Stuff = Other_Stuff

要在SELECT部件中使用字段,该字段必须存在于FROM部件中。

相关内容

  • 没有找到相关文章