首页 > 解决方案 > 影响单行内的多个(或所有)列的单个条件检查

问题描述

我想要完成的是影响所有行的多个列,例如column1 > 5更改或替换它们的值。

是否有任何优雅的方法可以执行一次条件检查(假设它是一个复杂的语句)并将其结果用于使用的列CASE / WHEN

我知道我可以使用WHERE column1 > 5and UNIONof sorts 执行标准过滤,但我想了解是否有任何其他选项(甚至可能是特定于 MySQL 的)可用。

编辑:

举个例子:

SELECT
CASE
    WHEN Country = 'UK' THEN CustomerId
    ELSE '???' 
END AS "CustomerId",
CASE
    WHEN Country = 'UK' THEN City
    ELSE '???' 
END AS "City",
CASE
    WHEN Country = 'UK' THEN Country
    ELSE '???' 
END AS "Country"
FROM Customers

如您所见,我在CASE WHEN Country = 'UK'这里多次使用,我想避免。

标签: mysqlsql

解决方案


您可以使用union all

select c.customerid, c.city, c.country
from customers c
where country = 'UK'
union all
select '???', '???', '???'
from customers c
where country is null or country <> 'UK'

推荐阅读