我需要在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的正确值。
什么查询将执行此操作?我在考虑加入,但我不确定是否可能。
当前回答
标准的SQL方法是
UPDATE ud
SET assid = (SELECT assid FROM sale s WHERE ud.id=s.id)
在SQL Server上,可以使用联接
UPDATE ud
SET assid = s.assid
FROM ud u
JOIN sale s ON u.id=s.id
其他回答
对于使用MySQL 5.7的prestashop用户
UPDATE
ps_stock_available sa
INNER JOIN ps_shop s
ON sa.id_shop = s.id_shop AND s.id_shop = 1
INNER JOIN ps_order_detail od
ON sa.id_product = od.product_id AND od.id_order = 22417
SET
sa.physical_quantity = sa.quantity + sa.reserved_quantity
这是一个例子,但重点正如埃里克在这里所说https://stackoverflow.com/a/1293347/5864034
您需要在FIRST处添加UPDATE语句,其中包含要连接的所有表的完整地址,然后添加SET语句
对于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');
SQL不是真正可移植的另一个例子。
对于MySQL,应该是:
update ud, sale
set ud.assid = sale.assid
where sale.udid = ud.id;
有关更多信息,请阅读多表更新:http://dev.mysql.com/doc/refman/5.0/en/update.html
UPDATE [LOW_PRIORITY] [IGNORE] table_references
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
我认为排名靠前的SQL Server将适用于Sybase,因为它们都是T-SQL,但不幸的是不是。
对于Sybase,我发现更新需要在表本身而不是别名上:
update ud
set u.assid = s.assid
from ud u
inner join sale s on
u.id = s.udid
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