sql - sqlite3中的case表达式

标签 sql sqlite case

有人告诉我在我正在阅读的一本书中使用这样的案例表达式:

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/

相关文章:

c# - 如何编写 Nhibernate 查询

PHP mysql_num_rows() 期望参数1为resource

.net - 如何在 .NET 中创建通用 SQL 参数?

c# - 同时具有 CASE 语句和 SUM 函数的 LINQ 查询

MySQL JOIN 三个表使用一个表的行值

sql - 奇怪的 mysql 查询执行时间行为

java - 获取位置并显示信息而不使用 if 语句?

ios - 使用 SQLITE 的 Swift 应用程序在更新数据库后崩溃。 SQLITE 文件未复制到文件/包

ios - iOS7 后台同步

sql - postgresql如何使用greatest function获取最大值的列名?