我需要在SQL Server中使用其“父”表中的数据更新此表,如下所示:
表:销售
id (int)
udid (int)
assid (int)
表:ud
id (int)
assid (int)
sale.assid包含更新ud.assid的正确值。
什么查询将执行此操作?我在考虑加入,但我不确定是否可能。
我需要在SQL Server中使用其“父”表中的数据更新此表,如下所示:
表:销售
id (int)
udid (int)
assid (int)
表:ud
id (int)
assid (int)
sale.assid包含更新ud.assid的正确值。
什么查询将执行此操作?我在考虑加入,但我不确定是否可能。
当前回答
使用JOIN多个表简化更新查询。
UPDATE
first_table ft
JOIN second_table st ON st.some_id = ft.some_id
JOIN third_table tt ON tt.some_id = st.some_id
.....
SET
ft.some_column = some_value
WHERE ft.some_column = 123456 AND st.some_column = 123456
请注意,first_table、second_table、third_table和123456这样的some_column是演示表名、列名和id。用有效名称替换它们。
其他回答
最简单的方法是使用SQL2005中引入的公共表表达式(CTE)
with cte as
(select u.assid col1 ,s.assid col2 from ud u inner join sale s on u.id = s.udid)
update cte set col1=col2
这在SQL Server中应该有效:
update ud
set assid = sale.assid
from sale
where sale.udid = id
Teradata Aster提供了实现目标的另一种有趣方式:
MERGE INTO ud --what table should be updated
USING sale -- from what table/relation update info should be taken
ON ud.id = sale.udid --join condition
WHEN MATCHED THEN
UPDATE SET ud.assid = sale.assid; -- how to update
对于SQLite,使用RowID属性进行更新:
update Table set column = 'NewValue'
where RowID =
(select t1.RowID from Table t1
join Table2 t2 on t1.JoinField = t2.JoinField
where t2.SelectValue = 'FooMyBarPlease');
UPDATE tblAppraisalBasicData
SET tblAppraisalBasicData.ISCbo=1
FROM tblAppraisalBasicData SI INNER JOIN aaa_test RAN ON SI.EmpID = RAN.ID