Conditional query in SQLite

﹥>﹥吖頭↗ 提交于 2020-01-07 07:48:29

问题


Way to do in sqlite what is typical in most DB?

if exists(select 1 from tosync where tbname = "%s" and tbid = %d 
   and (act = 1 and %d = 3 or act = 3 and %d = 1)
begin
  delete from tosync where tbname = "%s" and tbid = %d 
end
else
begin
  insert into tosync(tbname, tbid, act) values("%s", %d, %d);
end

Replaced values respectively are

 [TbName, tbid, act, act, TbName, tbid, TbName, tbid, act]

Please note, that this topic is not about UPSERT and similar issues available in sqlite.


回答1:


You can't do conditional queries in this way in SQLite.

You can however do INSERT ... WHERE NOT EXISTS ...

Check this out for more information... http://www.sqlite.org/lang_insert.html




回答2:


After a while solutuion was found for this particular situation.

I have to run both insert and delete queries in a row with same condition:

insert or replace into tosync (tbname,tbid,act) 
  select                        "%s" ,%d  ,%d 
where not exists(select 1 from tosync 
                 where tbname="%s" and tbid=%d and (act=1 and %d=3 or act=3 and %d=1));

delete from tosync 
where tbname="%s" and tbid=%d and exists(select 1 from
          tosync where tbname="%s" and tbid=%d and (act=1 and %d=3 or act=3 and %d=1));


来源:https://stackoverflow.com/questions/43011738/conditional-query-in-sqlite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!