MySQL mysql中选择案例中的案例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9236770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 12:06:02  来源:igfitidea点击:

case within a select case in mysql

mysqlcasenested

提问by Charles McAnany

I'm getting sick of trying to hook up to MSSQL, so I'm switching over to mysql. It's slow progress. Here's my current stumper: mssql:

我厌倦了尝试连接到 MSSQL,所以我切换到 mysql。这是缓慢的进展。这是我目前的绊脚石:mssql:

create function W(m varchar(255)) returns int begin

declare @e int
set @e = (select COUNT(N) from P where N = m)

declare @t int
set @t = dbo.C(m)

return case @t 
when 0 then -1 
when 1 then
    case @e when 0 then -1 else 1 end
when 2 then
    case @e when 1 then -1 when 2 then 0 when 3 then 0 when 4 then 1 end
when 3 then 
    case @e when 1 then -1 when 2 then 1 end
when 4 then 
    case @e when 1 then -1 when 2 then 0 when 3 then 1 end
end
end

I'd like to switch this to mysql. Is there a valid mysql way to:

我想将其切换到 mysql。是否有有效的 mysql 方法:

select select case n when 0 then 1 when 1 then 2 end into var

? How about

? 怎么样

set var = select case n when [...] end

?

?

回答by John Woo

this will guide you in using Inline IF and CASE statements in MySQL

这将指导您在 MySQL中使用内联 IF 和 CASE 语句

snippet:

片段:

SELECT CASE num_heads
           WHEN 0 THEN 'Zombie'
           WHEN 1 THEN 'Human'
           ELSE 'Alien'
        END AS race
FROM user

or

或者

mysql> SET @val := CASE num_heads
               WHEN 0 THEN 'Zombie'
               WHEN 1 THEN 'Human'
               ELSE 'Alien'
            END AS race;

mysql> SELECT @val;

回答by ruakh