历史给了我太多的子查询结果

history gives me too many subquery results

感谢您的帮助,希望我能够提供足够的信息。

我需要回滚与我们资产中的很多条目相关联的所有者 table(一个所有者被应用于很多系统)。我有一个历史记录 table,里面有我需要的信息,还有一个员工 table 被挤在那里,因为出于某种原因,历史记录 table 存储的是名字而不是 employee_id 的.

源数据: asset_tableasset_id, employee_id, asset_tag

employee_tableemployee_id, name

history_tableasset_id, old_name, new_name

update asset_table
set employee_id = (select employee_id
                   from employee_table
                   where name like (select old_name
                                    from history_table
                                    where asset_table.asset_id=history_table.asset_id
                                    and new_name like 'tobe replaced'))

但是,子查询每行出现多个结果。

我缺少什么来限制子查询结果?

MSSQL 服务器 2012

您可以使用 JOIN 代替子查询来编写如下更新语句,提供 table 结构和数据以便更正确的查询:

update at set at.employee_id = et.employee_id
from asset_table at
inner join history_table ht on at.asset_id = ht.asset_id
    and ht.new_name like '%tobe replaced%'
inner join employee_table et on et.name = ht.old_name
    and et.employee_id = at.employee_id

我想你需要一个历史上最后的人:

update at set
   employee_id = e.employee_id
from asset_table at
cross apply
(
  select top (1)
         h.old_name
    from history_table h
   where at.asset_id = h.asset_id
     and h.new_name = 'tobe replaced'
   order by h.<date or id or something> desc
) h
inner join employee_table e
   on e.name = h.old_name

TOP 1 将解决 "more than one result" 问题。

请注意,不带 %LIKE= 的工作方式完全相同。