gyn

Win32下的Perl,无用的select,停滞的Tk,结束吧....

sqlite无记录操作

Sqlite 中借鉴了 oracle db2 以及 postgresql 中得 null 操作方法,也就是借由 coalesce 的方法来处理 null 类型的数据。当遇到返回 null 数据时, coalesce 将第二个参数代替 null 。举例如下:

有表 phones
create table phones(name text, number integer);
insert into phones values(‘josh’, 86123413); 
insert into phones values(‘mariah’, 89804517);
insert into phones values(‘samantha’, NULL);

很不幸, samantha 的办公室还没有装电话,所以在表里虽然有她的名字但只能用 NULL 来做填充。如果有人希望在该数据库中查询她的电话时,将得到一个 NULL 的数据。当然首先是要设置 null 的表示字符串,通常情况下我们使用 ’NULL’ 来表示。为了更清楚地表达这种不存在的状况就需要使用 coalesce
Select coalesce(number, ‘no phone number for ’||name) as number from phones where name = ‘samantha’;

这样的查询可以得到合适的结果。至此似乎一切顺利,可事实上却忽视了一种最基本的情况。

Select coalesce(number, ‘no phone number for ’||name) as number from phones where name = ‘tata’;

公司里大概是没有一个叫 tata 的人,也许我们甚至难以确定他的性别。可是即便使用了 coalesce 也将一无所获。 Sqlite 里就是这样的,相关的文档里没有作出很好的解释。但它的确是返回了一个 NULL 值的,这个可以使用 nullif 来得到证实。
Select nullif((Select number from phones where name = ‘tata’), NULL) as result;

还好可以确定它返回了一个 NULL ,只要将 nullif 嵌到 coalesce 中便可以得到希望的结果了。
Select coalesce(nullif((Select number from phones where name = ‘tata’), NULL) , ‘no such person’) as result;

posted on 2006-12-17 14:46 gyn_tadao 阅读(508) 评论(1)  编辑 收藏 引用 所属分类: Database

评论

# re: sqlite无记录操作 2008-11-19 14:11 Don

我是这么理解这个问题的
Select coalesce(number, ‘no phone number for ’||name) as number from phones where name = ‘tata’;
还是使用这个例子 如果没有叫做 tata的人 那么返回的是个空的集合

如果存在tata这个人而这个人没有电话那么返回的是个个集合 其中的元素是个空值。 coalesce 的作用就是将这个空值变为'no phone number for....'.

BTW: coalesce 是标准SQL中的东西。  回复  更多评论   

只有注册用户登录后才能发表评论。
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿(15)

随笔分类(126)

随笔档案(108)

相册

搜索

最新评论

阅读排行榜

评论排行榜