【问题标题】:Exists function in update statement MS SQL Server在更新语句 MS SQL Server 中存在函数
【发布时间】:2019-02-01 20:32:03
【问题描述】:

我有 2 张桌子:

table0: (id,attr0,attr1)

table1: (id,attr0,attr1)

我需要用table1 值更新table0,其中t0.id = t1.id,使用exists 函数(避免加入函数)。我尝试过这样的事情:

UPDATE table0
SET
    attr0   = trn.attr0,
    attr1   = trn.attr1
FROM( 
    SELECT id, max(transaction_date) as attr0,
    max(CASE 
            WHEN transaction_code in ('a', 'b', 'c')
            THEN transaction_date  
            ELSE NULL 
        END) as attr1
    FROM table1
    GROUP BY id) trn
WHERE exists (SELECT * FROM table1 WHERE table0.id = trn.id);

但是这个查询更新了table0 中的所有行,我不明白为什么。 请告诉我,为什么它会出错?

【问题讨论】:

  • exists(SELECT * FROM table1 WHERE table0.id = trn.id) 这部分缺少连接谓词到table1
  • 因为 FROM 子句中的 table0 没有任何条件。
  • 请添加一些示例数据。尚不清楚为什么But this query updates all rows 是不正确的行为。
  • 例如 table0 有 10 行(id - 从 0 到 9),但是在“FROM”(trn table)查询的结果中有 9 行(id - 从 0 到 8) .此语句更新 table0 中的所有 10 行(id = 9 的行更新随机数据)。我在“WHERE”条件下写了什么?
  • 请用简单的重现来更新您的问题,以证明这种行为。 Sqlfiddle 会很好。

标签: sql-server tsql sql-update exists


【解决方案1】:

你能用这个吗?这只会更新 table1 中的 ID

with cte as (
SELECT id, max(transaction_date) as attr0,
max(CASE 
        WHEN transaction_code in ('a', 'b', 'c')
        THEN transaction_date  
        ELSE NULL 
    END) as attr1
    FROM table1 a

    GROUP BY id
    )
    update dbo.table0
    set
    attr0 = cte.attr0,
    attr1 = cte.attr1
    from cte where cte.id = table0.id

【讨论】:

    【解决方案2】:

    请尝试以下方法

    UPDATE t0
    SET
        attr0   = trn.attr0,
        attr1   = trn.attr1
    FROM table0 t0 join( 
        SELECT id, max(transaction_date) as attr0,
        max(CASE 
                WHEN transaction_code in ('a', 'b', 'c')
                THEN transaction_date  
                ELSE NULL 
            END) as attr1
        FROM table1
        GROUP BY id)trn on trn.id=t0.id
    

    谢谢

    【讨论】:

      【解决方案3】:

      使用内连接可以更新数据。如下所示。

      UPDATE t
      SET
          t.attr0   = trn.attr0,
          t.attr1   = trn.attr1
      FROM( 
          SELECT id, max(transaction_date) as attr0,
          max(CASE 
                  WHEN transaction_code in ('a', 'b', 'c')
                  THEN transaction_date  
                  ELSE NULL 
              END) as attr1
          FROM table1
          GROUP BY id) trn
      INNER JOIN table0 t ON t.id=trn.id
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-04
        • 2021-02-19
        • 2021-12-03
        • 1970-01-01
        • 2013-07-06
        • 2016-12-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多