SQLite 实现if not exist 类似功能的操作

需要实现:

if not exists(select * from errorconfig where type='retrywaitseconds')
begin
  insert into errorconfig(type,value1)
  values('retrywaitseconds','3')
end

只能用:

insert into errorconfig(type,value1)
select 'retrywaitseconds','3'
where not exists(select * from errorconfig where type='retrywaitseconds')

因为 sqlite 中不支持sp

补充:sqlite3中not in 不好用的问题

在用sqlite3熟悉sql的时候遇到了一个百思不得其解的问题,也没有在google上找到答案。虽然最后用“迂回”的方式碰巧解决了这个问题,但暂时不清楚原理是什么,目前精力有限,所以暂时记录下来,有待继续研究。

数据库是这样的:

create table book (
 id integer primary key,
 title text,
 unique(title)
);
create table checkout_item (
 member_id integer,
 book_id integer,
 movie_id integer,
 unique(member_id, book_id, movie_id) on conflict replace,
 unique(book_id),
 unique(movie_id)
);
create table member (
 id integer primary key,
 name text,
 unique(name)
);
create table movie (
 id integer primary key,
 title text,
 unique(title)
);

该数据库包含了4个表:book, movie, member, checkout_item。其中,checkout_item用于保存member对book和movie的借阅记录,属于关系表。

问一:哪些member还没有借阅记录?

sql语句(sql1)如下:

select * from member where id not in(select member_id from checkout_item);

得到了想要的结果。

问二:哪些book没有被借出?

这看起来与上一个是类似的,于是我理所当然地运行了如下的sql语句(sql2):

select * from book where id not in(select book_id from checkout_item);

可是——运行结果没有找到任何记录! 我看不出sql2与sql1这两条语句有什么差别,难道是book表的问题?于是把not去掉,运行了如下查询语句:

select * from book where id in(select book_id from checkout_item);

正确返回了被借出的book,其数量小于book表里的总行数,也就是说确实是有book没有借出的。

接着google(此处省略没有营养的字),没找到解决方案。可是,为什么member可以,book就不可以呢?它们之前有什么不同?仔细观察,发现checkout_item里的book_id和movie_id都加了一个unique,而member_id则没有。也许是这个原因?不用id了,换title试试:

select * from book where 
 title not in( 
 select title from book where id in(
 select book_id from checkout_item));

确实很迂回,但至少work了。。。

问题原因:当not碰上null

事实是,我自己的解决方案只不过是碰巧work,这个问题产生跟unique没有关系。邱俊涛的解释是,“select book_id from checkout_item”的结果中含有null值,导致not也返回null。当一个member只借了movie而没有借book时,产生的checkout_item中book_id就是空的。

解决方案是,在选择checkout_item里的book_id时,把值为null的book_id去掉:

select * from book where id not in(select book_id from checkout_item where book_id is not null);

总结

我在解决这个问题的时候方向是不对的,应该像调试程序一样,去检查中间结果。比如,运行如下语句,结果会包含空行:

select book_id from checkout_item

而运行下列语句,结果不会包含空行:

select member_id from checkout_item

这才是sql1与sql2两条语句执行过程中的差别。根据这个差别去google,更容易找到答案。当然了,没有null概念也是我“百思不得其解”的原因。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。如有错误或未考虑完全的地方,望不吝赐教。

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐