如何在 SQL Server 中使用 JOIN 执行 UPDATE 语句? [英] How can I do an UPDATE statement with JOIN in SQL Server?
问题描述
我需要使用其父"表中的数据更新 SQL Server 中的此表,请参见下文:
I need to update this table in SQL Server with data from its 'parent' table, see below:
表:销售
id (int)
udid (int)
assid (int)
表:ud
id (int)
assid (int)
sale.assid
包含更新 ud.assid
的正确值.
sale.assid
contains the correct value to update ud.assid
.
什么查询会这样做?我正在考虑 join
但不确定是否可行.
What query will do this? I'm thinking of a join
but I'm not sure if it's possible.
推荐答案
语法严格取决于您使用的 SQL DBMS.这里有一些方法可以在 ANSI/ISO(又名应该适用于任何 SQL DBMS)、MySQL、SQL Server 和 Oracle 中执行此操作.请注意,我建议的 ANSI/ISO 方法通常比其他两种方法慢得多,但如果您使用的是 MySQL、SQL Server 或 Oracle 以外的 SQL DBMS,那么它可能是唯一的方法(例如如果您的 SQL DBMS 不支持 MERGE
):
Syntax strictly depends on which SQL DBMS you're using. Here are some ways to do it in ANSI/ISO (aka should work on any SQL DBMS), MySQL, SQL Server, and Oracle. Be advised that my suggested ANSI/ISO method will typically be much slower than the other two methods, but if you're using a SQL DBMS other than MySQL, SQL Server, or Oracle, then it may be the only way to go (e.g. if your SQL DBMS doesn't support MERGE
):
ANSI/ISO:
update ud
set assid = (
select sale.assid
from sale
where sale.udid = ud.id
)
where exists (
select *
from sale
where sale.udid = ud.id
);
MySQL:
update ud u
inner join sale s on
u.id = s.udid
set u.assid = s.assid
SQL 服务器:
update u
set u.assid = s.assid
from ud u
inner join sale s on
u.id = s.udid
PostgreSQL:
PostgreSQL:
update ud
set assid = s.assid
from sale s
where ud.id = s.udid;
注意,Postgres 的 FROM
子句中不能重复目标表.
Note that the target table must not be repeated in the FROM
clause for Postgres.
甲骨文:
update
(select
u.assid as new_assid,
s.assid as old_assid
from ud u
inner join sale s on
u.id = s.udid) up
set up.new_assid = up.old_assid
SQLite:
update ud
set assid = (
select sale.assid
from sale
where sale.udid = ud.id
)
where RowID in (
select RowID
from ud
where sale.udid = ud.id
);
这篇关于如何在 SQL Server 中使用 JOIN 执行 UPDATE 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!