首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >案例在sqlite3中的表达

案例在sqlite3中的表达
EN

Stack Overflow用户
提问于 2014-11-17 02:29:40
回答 2查看 2.2K关注 0票数 2

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

代码语言:javascript
复制
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;

但是,这给我带来了一个错误:

执行查询时出错:没有这样的列:说明

我想要做的是避免空值。那它哪里出问题了?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-11-17 03:04:46

您编写的查询在SQL的任何方言中都不起作用(对不起,但示例不起作用)。您可以使用子查询来做您想做的事情:

代码语言:javascript
复制
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

票数 1
EN

Stack Overflow用户

发布于 2014-11-17 02:45:48

我敢打赌,“食品”表没有“描述”列,您希望WHERE子句能够从case语句中获取列别名。

它不应该那样做。在标准SQL中,WHERE子句在SELECT子句之前进行计算。这意味着您在SELECT子句中提供的任何别名对于WHERE子句都不可用。但SQLite允许这样做。(见下文。我还没有在文档中找到这个“特性”。)

你可能在找这个。

代码语言:javascript
复制
where type_id is not null

或者你可能在找这个。

代码语言:javascript
复制
where type_id not in (7, 8, 9, 13)

从技术上讲,如果SQL引擎想要符合SQL标准,它只需要在SELECT子句之前评估WHERE子句。对像我们这样的程序员的影响是一样的。

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26964611

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档