我需要在SQL Server中使用"父"表中的数据更新此表,请参见以下内容:
Table: sale
id (int)
udid (int)
assid (int)
Table: ud
id (int)
assid (int)
sale.assid
包含要更新ud.assid
的正确值.
什么查询可以做到这一点?我在考虑join
分,但我不确定是否可能.
我需要在SQL Server中使用"父"表中的数据更新此表,请参见以下内容:
Table: sale
id (int)
udid (int)
assid (int)
Table: ud
id (int)
assid (int)
sale.assid
包含要更新ud.assid
的正确值.
什么查询可以做到这一点?我在考虑join
分,但我不确定是否可能.
语法严格取决于您使用的SQL DBMS.以下是一些在ANSI/ISO(aka应该适用于任何SQL DBMS)、MySQL、SQL Server和Oracle中实现这一点的方法.请注意,我建议的ANSI/ISO方法通常比其他两种方法慢得多,但如果您使用的是SQL DBMS,而不是MySQL、SQL Server或Oracle,那么这可能是唯一的方法(例如,如果您的SQL DBMS不支持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 Server:
update u
set u.assid = s.assid
from ud u
inner join sale s on
u.id = s.udid
PostgreSQL:
update ud
set assid = s.assid
from sale s
where ud.id = s.udid;
请注意,对于Postgres,目标表不能在FROM
子句中重复.
神谕:
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
);