在我正在读的一本书中,有人告诉我要使用这样的用例表达式:
select name || case type_id
when 7 then ' is a drink'
when 8 then ' is a fruit'
when 9 then ' is junkfood'
when 13 then ' is seafood'
else null
end description
from foods
where description is not null
order by name
limit 10;但是,这给我带来了一个错误:
执行查询时出错:没有这样的列:说明
我想要做的是避免空值。那它哪里出问题了?
发布于 2014-11-17 03:04:46
您编写的查询在SQL的任何方言中都不起作用(对不起,但示例不起作用)。您可以使用子查询来做您想做的事情:
select description
from (select name || (case type_id
when 7 then ' is a drink'
when 8 then ' is a fruit'
when 9 then ' is junkfood'
when 13 then ' is seafood'
else ''
end) as description,
name
from foods
) f
where description is not null
order by name
limit 10;注意,我将else子句更改为空子字符串,而不是NULL。
发布于 2014-11-17 02:45:48
我敢打赌,“食品”表没有“描述”列,您希望WHERE子句能够从case语句中获取列别名。
它不应该那样做。在标准SQL中,WHERE子句在SELECT子句之前进行计算。这意味着您在SELECT子句中提供的任何别名对于WHERE子句都不可用。但SQLite允许这样做。(见下文。我还没有在文档中找到这个“特性”。)
你可能在找这个。
where type_id is not null或者你可能在找这个。
where type_id not in (7, 8, 9, 13)
从技术上讲,如果SQL引擎想要符合SQL标准,它只需要在SELECT子句之前评估WHERE子句。对像我们这样的程序员的影响是一样的。
sqlite> create table foods (name varchar(15), type_id integer);
sqlite> insert into foods values ('Tequila', 7), ('Apple', 8),
...> ('Twinkie', 9), ('Tuna', 13), ('Olive oil', null);
sqlite> select name || case type_id
...> when 7 then ' is a drink'
...> when 8 then ' is a fruit'
...> when 9 then ' is junkfood'
...> when 13 then ' is seafood'
...> else null
...> end description
...> from foods
...> where description is not null
...> order by name
...> limit 10;
Apple is a fruit
Tequila is a drink
Tuna is seafood
Twinkie is junkfoodhttps://stackoverflow.com/questions/26964611
复制相似问题