如果用CASE语句重新评估MySQL列,然后使用同名别名,如何引用别名?

时间:2019-03-26 14:47:53

标签: mysql

我正在使用CASE语句评估列,然后为其别名与列相同的名称。然后如何强制MySQL选择重新评估的值而不是原始值?

SELECT
store,
CASE 
        WHEN offer IN ("offer 1", "offer 2") THEN "books"
        ELSE offer
END AS offer,

DATE(datetime) as date,

concat(COALESCE(store, ""), COALESCE((select offer)," ")) as connector

FROM sales_1 ORDER BY datetime DESC

在上面的代码中,“ concat”函数使用原始的“ offer”值,而不是我在CASE语句中更改的值。 我知道我可以在COALESCE(...)中执行另一个CASE,但是必须有一种更简单的方法。

1 个答案:

答案 0 :(得分:0)

问题出在COALESCE((select offer)。您正在从没有表中选择列报价。从语法上讲这是不正确的。

您已经提出了一种实现预期结果的方法。另一种方法是使用如下所示的子查询。

SELECT
    A.store,
    A.offer,
    A.`date`
    CONCAT(COALESCE(store, ""), COALESCE(A.offer," ")) AS connector
FROM
    (SELECT
       DISTINCT
       store,
       CASE WHEN offer IN ("offer 1", "offer 2") THEN "books"
            ELSE offer
       END AS offer,
       DATE(datetime) AS `date`
    FROM sales_1 
    ORDER BY `datetime` DESC) A;