2013-07-22 134 views
1

我想弄清楚如何在影響兩個表的SQL中進行復雜的更新。基於另一個表中的值的SQL if/else更新表

我的2代表的樣子:

t1: key, val_1 (with key as the primary key) 
    t2: t1_key, user_id, val_2 (with t1_key and user_id as the primary key) 

我需要弄清楚是怎麼做它說的更新,給定一個user_ID的 「U」 和一鍵 「K」:

if (["u"+"k"] does not exist at all in t2) { 
    update t1.val = t1.val+1 where key="k"; 
    insert ("u","k",1) into t2; 
    } else if (["u"+"k"] exists in t2 and val_2 < 1) { 
    update t1.val = t1.val+1 where key="k"; 
    update t2.val2 = t2.val2+1 where t1_key="k" AND user_id="u"; 
    } 

有什麼建議嗎?

+1

您正在使用哪種RDBMS? –

+0

Microsoft SQL服務器 – Korra

+0

可怕的問題:) –

回答

0

那麼,你的僞代碼看起來就像一個查詢。我打出來的SQL搗鼓你: http://sqlfiddle.com/#!3/19597d/11

declare @k int = 3 
declare @user_id int = 1 

if not exists (select * from t2 
       where user_id = @user_id 
       and t1_k = @k) begin 
    update t1 set val = val + 1 where k = @k 
    insert t2 values (@k, @user_id, 1) 
end else if 
    exists (select * from t2 
      where user_id = @user_id 
      and t1_k = @k 
      and val < 1) begin 
    update t1 set val = val + 1 where k = @k 
    update t2 set val = val + 1 
    where t1_k = @k 
    and user_id = @user_id 
end 

select * from t1; 
select * from t2; 

當你去實現這一點,雖然,你會想要交易。 (小提琴似乎不喜歡那樣。)

不確定你是否意味着某些情況下不做任何事情,但是你的代碼沒有最後的else子句。

+0

完美!我認爲BEGIN-END是我失蹤的作品。謝謝! – Korra

相關問題