如何在查询中重用派生值

时间:2014-05-29 20:52:08

标签: mysql

必须有一种更有效的方法来做到这一点,但我还不熟悉mySQL,知道要研究哪些术语。我一直在关注AS关键字。

以下是我的工作查询。看看我如何多次导出持续时间(TIME_TO_SEC(TIMEDIFF(FinishTime,StartTime))。是否可以导出一次并在此查询中重复使用它?

table: AuraUsers
fields: ID, StartTime, FinishTime, Completed


SELECT 
    TIME_TO_SEC(
        TIMEDIFF(
            FinishTime,
            StartTime
        )
    ) 
    AS json 
    FROM AuraUsers 
    WHERE (
        StartTime IS NOT NULL 
        AND 
        FinishTime IS NOT NULL 
        AND 
        Completed=7 
        AND 
        TIME_TO_SEC(
            TIMEDIFF(
                FinishTime,
                StartTime
            )
        ) > 0 
        AND 
        TIME_TO_SEC(
            TIMEDIFF(
                FinishTime,
                StartTime
            )
        ) < 90275
    ) 
    ORDER BY TIME_TO_SEC(
        TIMEDIFF(
            FinishTime,
            StartTime
        )
    ) DESC 
    LIMIT 0,535;

1 个答案:

答案 0 :(得分:0)

使用HAVING子句,但实际上并没有重用它会在每次使用查询中的别名时评估整个表达式

SELECT 
    TIME_TO_SEC(
        TIMEDIFF(
            FinishTime,
            StartTime
        )
    ) 
    AS json 
    FROM AuraUsers 
    HAVING (
        StartTime IS NOT NULL 
        AND 
        FinishTime IS NOT NULL 
        AND Completed=7 
        AND json > 0 
        AND json < 90275
    ) 
    ORDER BY json DESC 
    LIMIT 0,535;