如何为CASE WHEN THEN SELECT语句赋予别名

时间:2018-08-09 19:40:54

标签: mysqli case

我有以下sql:

SELECT id,memberID AS member,
    CASE 
    WHEN svDate<>"0000-00-00 00:00:00" THEN svDate
    WHEN repeatStartDate<>"0000-00-00 00:00:00" THEN repeatStartDate
    WHEN vvStartDate<>"0000-00-00 00:00:00" THEN vvStartDate
    END
FROM services  
ORDER BY `CASE 
    WHEN svDate<>"0000-00-00 00:00:00" THEN svDate
    WHEN repeatStartDate<>"0000-00-00 00:00:00" THEN repeatStartDate
    WHEN vvStartDate<>"0000-00-00 00:00:00" THEN vvStartDate
    END` DESC

谁能告诉我如何给这个大写的语句加上dateBeg的别名,以便我可以在字段选择(SELECT id,member,dateBeg)以及ORDER BY子句(ORDER BY dateBeg)中使用dateBeg

1 个答案:

答案 0 :(得分:0)

您可以将CASE别名为dateBeg,如下所示;

SELECT id,memberID AS member,
CASE 
WHEN svDate<>"0000-00-00 00:00:00" THEN svDate
WHEN repeatStartDate<>"0000-00-00 00:00:00" THEN repeatStartDate
WHEN vvStartDate<>"0000-00-00 00:00:00" THEN vvStartDate
END AS dateBeg
FROM services 

AS关键字通常不是必需的,因此END dateBag也应该工作。

关于ORDER BY,您现在可以使用已设置的dateBag引用。

SELECT id,memberID AS member,
CASE 
WHEN svDate<>"0000-00-00 00:00:00" THEN svDate
WHEN repeatStartDate<>"0000-00-00 00:00:00" THEN repeatStartDate
WHEN vvStartDate<>"0000-00-00 00:00:00" THEN vvStartDate
END AS dateBeg
FROM services 
ORDER BY dateBeg DESC