有人告诉我在我正在阅读的一本书中使用这样的案例表达式:
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;
但是,这给了我一个错误:
Error while executing query: no such column: description
我想要做的是避免空值。那么到底哪里出了问题呢?
最佳答案
我敢打赌“foods”表没有“description”列,并且您希望 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 junkfood
关于sql - sqlite3中的case表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26964611/