2017-03-25 57 views
0

sqlite中的做法在大多數數據庫中,典型的是什麼?SQLite中的條件查詢

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] 

請注意,這個話題在sqlite的可用不是UPSERT和類似的問題。

+0

是UPSERT一個新的東西?首先你需要聲明你的變量 – Edward

+0

@愛德華你是什麼意思? – notricky

+0

@愛德華,對不起,但你最後的評論並沒有讓你對我的第一個問題更清楚。但我想大多數UPSERT不是一件新事物。 – notricky

回答

0

你不能在SQLite中以這種方式進行條件查詢。

但是你可以做INSERT ... WHERE NOT EXISTS ...

看看這個以獲取更多信息...... http://www.sqlite.org/lang_insert.html

+0

你是否建議在'INSERT'和'DELETE'語句中複製'WHERE'條件來一個接一個地運行多個查詢? – notricky

+0

我沒有真正提出建議,只是回答你的問題。就我個人而言,我可能會嘗試最初運行一個SELECT,有條件地在我的代碼上執行,然後運行適當的查詢。但是我不知道你的背景,因爲你沒有說過。 –

+0

我明白了。我也在想這個,但是我仍然希望能夠在一個sql查詢中完成...... – notricky

0

一會兒solutuion後,發現這種特殊的情況。

我要運行INSERT和一排與相同條件刪除查詢:

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