2013-07-22 86 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

相关问题