在select中使用变量

时间:2017-02-16 19:04:23

标签: mysql subquery case

我有这样的查询

SELECT ID, ... , 
       (SELECT MAX(EndDate) FROM Projects) As NewestDate,
       (CASE
           WHEN (NewestDate > NOW()) THEN 'More Work is coming'  
           ELSE 'Send Vendors to work' 
       END) Message
FROM SOME_TABLE

即。我试图在CASE中使用NewestDate的值。这可能吗?或者这样的事情可能吗?

由于

2 个答案:

答案 0 :(得分:1)

直接否。您可以使用相同的声明两次:

SELECT ID, ... , 
       (SELECT MAX(EndDate) FROM Projects) As NewestDate,
       (CASE
           WHEN ((SELECT MAX(EndDate) FROM Projects) > NOW()) 
           THEN 'More Work is coming'  
           ELSE 'Send Vendors to work' 
       END) Message
FROM SOME_TABLE

如果要使用已经计算过的,请使用子查询:

select t.*,
    (
        case 
            when (NewestDate > NOW())
                then 'More Work is coming'
            else 'Send Vendors to work'
            end
        ) Message
from (
    select ID,
        ...,
        (
            select MAX(EndDate)
            from Projects
            ) as NewestDate
    from SOME_TABLE
    ) t;

答案 1 :(得分:0)

您可以加入最新的日期。这比每行的子查询更快。

SELECT ID, ... , 
       nd.NewestDate,
       (CASE
           WHEN (nd.NewestDate > NOW()) THEN 'More Work is coming'  
           ELSE 'Send Vendors to work' 
       END) Message
FROM SOME_TABLE
JOIN (
    SELECT MAX(EndDate) AS NewestDate FROM Projects
) nd