MySql在SELECT语句中使用CASE时的多个输出

时间:2014-04-23 13:34:31

标签: mysql sql

使用案例时,如何才能在结果中得出两件事?

例如:

set @x = 1;

select case when UserId = @x 
then
concat('Test'), // This is the part I fail at. It'll output either one, but not more.
userName 
end from my_members;

2 个答案:

答案 0 :(得分:2)

您需要两个case语句:

set @x = 1;

select (case when UserId = @x then concat('Test') end) as col1
       (case when UserId = @x then userName end) as userName
from my_members;

我个人希望case语句允许多列返回,但这需要对SQL进行大量更改。

答案 1 :(得分:0)

另一种方法是使用@x作为过滤谓词,然后将CASE的两个/所有分支替换为UNION,选择性地定位每个分支,例如:< / p>

select UserId, concat('Test', userName) as userName
from my_members
WHERE UserId = @x

UNION 

select UserId, userName
from my_members
WHERE UserId <> @x;

SqlFiddle here