【发布时间】: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