在 case 的 then 子句中使用 select 语句

G o*_*one 3 mysql case

我试图在thenofcase语句中包含 select 语句,但输出不符合预期。我知道有不同的方法可以做到这一点,但是可以按照我想要的方式完成吗?

使用以下示例数据:

create table example(name varchar(10));

insert into example values
('abc'),('bcd'),('xyz');
Run Code Online (Sandbox Code Playgroud)

我已经尝试过这个查询(这里是小提琴

select 
case when ((select * from example where name='abc')>=1)
then (select * from example where name='abc')
else (select count(*) from example)
end
from example
Run Code Online (Sandbox Code Playgroud)

但它输出

3
3
3

预期输出(如果name='abc'存在)

name
abc
Run Code Online (Sandbox Code Playgroud)

如果不是count(*)

提前致谢

lc.*_*lc. 5

示例中的子查询是(select * from example where name='abc')结果集,而不是标量值。目前它“有效”,因为它将表中的唯一列与值进行比较1,但如果表中有多于一列,则会出错。也许你有意(select count(*) from example where name='abc')

同样,case 中的 THEN 子句只能用于提供单个列值。为了做到这一点,也许您的意思如下:

select 
    case when exists (select * from example where name='abc')
              then (select name from example where name='abc')
         else (select count(*) from example)
    end
from example
Run Code Online (Sandbox Code Playgroud)

但即使在这里,您也会得到三行,并且行和结果集之间没有相关性example,所以我不太确定您要做什么。我想还有一个更高的目标,所以我就这样吧。