【问题标题】:SQL if/else update table based on value in another tableSQL if/else 根据另一个表中的值更新表
【发布时间】:2013-07-22 16:12:33
【问题描述】:

我试图弄清楚如何在影响两个表的 SQL 中进行复杂的更新。

我的 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)

我需要弄清楚的是如何在给定用户 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";
  }

有什么想法吗?

【问题讨论】:

  • 您使用的是哪个 RDBMS?

标签: sql sql-update sql-insert


【解决方案1】:

嗯,你的伪代码看起来就像一个查询。我在 SQL Fiddle 上为您输入了它: 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 子句。

【讨论】:

  • 完美!我认为 BEGIN-END 是我缺少的部分。谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 2022-01-10
相关资源
最近更新 更多