我需要在SQL Server中使用其“父”表中的数据更新此表,如下所示:

表:销售

id (int)
udid (int)
assid (int)

表:ud

id  (int)
assid  (int)

sale.assid包含更新ud.assid的正确值。

什么查询将执行此操作?我在考虑加入,但我不确定是否可能。


当前回答

对于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 table1
SET    COLUMN = value
FROM   table2,
       table3
WHERE  table1.column_id = table2.id
       AND table1.column_id = table3.id
       AND table1.COLUMN = value
       AND table2.COLUMN = value
       AND table3.COLUMN = value 

对于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');

最简单的方法是使用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 DBMS。以下是在ANSI/ISO(也就是任何SQL DBMS)、MySQL、SQL Server和Oracle中实现这一点的一些方法。请注意,我建议的ANSI/ISO方法通常比其他两种方法慢得多,但如果您使用的是MySQL、SQL Server或Oracle以外的SQL DBMS,那么这可能是唯一的方法(例如,如果您的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(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
 );

在MS ACCESS中:

UPDATE ud 
INNER JOIN sale ON ud.id = sale.udid
SET ud.assid = sale.assid;