gpt4 book ai didi

mysql - 在 SQL 中的 case..when 语句中,当单个条件为真时,我可以执行多个表达式吗?

转载 作者:行者123 更新时间:2023-11-29 00:36:02 25 4
gpt4 key购买 nike

我想在 SQL 中的 case..when 语句中当单个条件为真时显示多个语句。

例如:

case when (condition is true) then 
print "A"
print "B"
.
.
.
.
print "Z"
when (condition2 is true) then
print "Z"
print "Y"
.
.
.
.
print "A

end

谁能给我提供它的确切语法?提前致谢。

最佳答案

如果您的条件很复杂,您可以将其移至子查询。这样你就不必为每一列重复它:

select  case when Condition = 1 then 'A' else 'B' end
, case when Condition = 1 then 'C' else 'D' end
, case when Condition = 1 then 'E' else 'F' end
, ...
from (
select *
, case
when ... complex condition ... then 1
else 0
end as Condition
from YourTable
) as SubQueryAlias

另一个选项是与 CTE 的联合(并非在所有数据库中都可用。)它允许您在不使用 case 的情况下为两者编写表达式,并且由于 CTE,条件不会重复。

;       with CteAlias as
(
select *
, case
when ... complex condition ... then 1
else 0
end as Condition
from YourTable
)
select 'A', 'C', 'E'
from CteAlias
where Condition = 1
union all
select 'B', 'D', 'F'
from CteAlias
where Condition = 0

关于mysql - 在 SQL 中的 case..when 语句中,当单个条件为真时,我可以执行多个表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14274187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com