比较2个表并根据结果更新一列?

时间:2018-08-03 18:08:38

标签: sql sql-server

我有下表:

TableA

Category  Code Sub
           AA   CS
           AB   CD
  TK       AS

TableB

Category  Code Sub  Found
  D1       AA   CS    0
           AA   CS    0
  D3            CD    0
  TK       AS         0

我如何使用TableA将TableB更新为以下内容,如果发现整行与TableA中的行匹配,发现的行将等于1?

Category  Code Sub  Found
  D1       AA   CS    0
           AA   CS    1
  D3            CD    0
  TK       AS         1

3 个答案:

答案 0 :(得分:1)

我会使用exists

update b
      set b.found = 1
from tableb b
where exists (select 1 
              from tablea a 
              where b.category = a.category and 
                    b.code = a.code and 
                    b.sub = a.sub
             );

答案 1 :(得分:0)

您可以使用join

update b
    set found = 1
    from b join
         a
         on b.category = a.category and b.code = a.code and b.sub = a.sub;

这假定空格为空字符串,而不是NULL

如果它们是null,则性能可能会受到影响,但是您可以这样做:

update b
    set found = 1
    from b join
         a
         on (b.category = a.category or b.category is null and a.category is null) and
            (b.code = a.code or b.code is null and a.code is null) and
            (b.sub = a.sub or b.sub is null and a.sub is null);

答案 2 :(得分:0)

您可以使用以下查询,该查询使用JOIN联接TableA和TableB,并在联接时使用COALESCE处理空值:

UPDATE
        tb
SET
        Found = 1
FROM
        TableB tb
    JOIN
        TableA ta
            ON COALESCE(tb.Category, 0) = COALESCE(ta.Category, 0)
               AND COALESCE(tb.Code, 0) = COALESCE(ta.Code, 0)
               AND COALESCE(tb.Sub, 0) = COALESCE(ta.sub, 0);