【问题标题】:Conditional query in SQLiteSQLite 中的条件查询
【发布时间】:2017-03-25 02:08:40
【问题描述】:

如何在 sqlite 中执行大多数 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

替换的值分别是

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

请注意,本主题与UPSERT 和 sqlite 中的类似问题无关。

【问题讨论】:

  • 更新插入是新事物吗?首先你需要声明你的变量
  • @Edward 你是什么意思?
  • @Edward,对不起,但你的最后评论并没有让我更清楚你的第一个问题。但我想这对于大多数 UPSERT 来说并不是什么新鲜事。
  • 好吧,我对 SQLite 并不熟悉,但我确实了解 T-SQL,只是说我从未听说过 UPSERT,我想可能是拼写错误。话虽如此,我什至刚刚参加了 Microsoft 数据库基础考试,我可以说其中有 0 分,或者关于 UPSERT 的学习指南
  • @Edward,我明白了。那么是的,在 SQLite 中它是一个选项。执行UPDATE OR INSERT有效。在下面由 Rik Lewis 发表的评论中查看更多信息。

标签: sqlite exists


【解决方案1】:

您不能在 SQLite 中以这种方式进行条件查询。

但是你可以在不存在的地方插入 ...

查看这里以获取更多信息...http://www.sqlite.org/lang_insert.html

【讨论】:

  • 您是否建议通过在INSERTDELETE 语句中复制WHERE 条件来逐个运行多个查询?
  • 我并不是真的提出建议,只是回答您的问题。就我个人而言,我最初可能会尝试运行 SELECT,对我的代码有条件地执行,然后运行适当的查询。但我不知道你的背景,正如你没有说的那样。
  • 我明白了。我也在考虑这个,但我仍然希望可以在一个 sql-query 中完成......
  • 我花了很多时间却没有找到关于该问题的任何其他问题,这对我来说真的很奇怪。
  • 对不起,我认为这不可能。
【解决方案2】:

一段时间后,针对这种特殊情况找到了解决方案。

我必须以相同的条件连续运行插入和删除查询:

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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    相关资源
    最近更新 更多