问题描述
我有以下工作代码(MySql 8.0):
select user_id as "user",(case when userBad then CodeRed
else CodeBlue
end)
From colours
我想为CodeRed列分配别名Red,为CodeBlue列分配别名Blue。我知道我不能在case语句中使用别名。那么分配条件别名的正确语法是什么?我以为也许我声明了一个字符串变量来保存别名的值,然后将该变量附加到case语句中:
declare alias varchar(4);
if userBad then set alias = "Red"
else set alias = "Blue";
select user_id as "user",(case when userBad then CodeRed
else CodeBlue
end) as alias
From colours;
但是,正如您可能期望的那样,我最后得到一列称为别名!那么有没有一种方法可以根据案例选择来分配条件别名?谢谢
更新:Slava通过使用准备好的语句来别名化变量提供了一个很好的解决方案。我的完整代码:我现在收到错误1054:“字段列表”中的未知列userBad,但我相信Slava已将我带入正确的轨道。
PROCEDURE `Test`(userBad bool)
BEGIN
declare alias varchar(4);
drop temporary table if exists colours;
create temporary table colours (user_id int,codeRed int,codeBlue int);
if userBad then set alias = "Red";
else set alias = "Blue";
end if;
SET @sql = CONCAT('select user_id as "user",(case when userBad = true then codeRed
else codeBlue
end) as ',alias,' from colours');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
最终更新:我已经解决了“ 1054:“字段列表”中的未知列userBad”错误。我在下面发布了完整的工作解决方案。感谢Slava,让我正确地使用了准备好的语句。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)