简体   繁体   English

使用 SQL 在具有重复数据的表之间插入

[英]Using SQL to insert between tables with repeating data

My data is structured as follows:我的数据结构如下:

Table 1 - Employee</b>

-ID
-Name
-Address
-City
-State
...

Table 2 - Audit

-Address
-City
-State
...

I need to insert the corresponding id from the employee table into the audit table by matching the address, city, and state from the smaller audit table with address information from the larger employee table (with the assumption that no employees share an address)我需要通过较小审计表中的地址、城市和州与较大雇员表中的地址信息相匹配(假设没有雇员共享地址),将雇员表中的相应 id 插入审计表中

Here is the code I have been working with, the query generates the data that I want, but the update, set sequence fails with the following message:这是我一直在使用的代码,查询生成了我想要的数据,但更新、设置序列失败并显示以下消息:

Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1 value.消息 512,级别 16,状态 1,第 1 行子查询返回了 1 个以上的值。 This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.当子查询跟随 =、!=、<、<=、>、>= 或当子查询用作表达式时,这是不允许的。

UPDATE AuditTable SET employee_id = (
    SELECT e.employee_id 
    FROM EmployeeTable e 
    JOIN AuditTable a
        ON  e.address = a.address
        AND e.home_city = a.home_city
        AND e.home_st = a.home_st
)

The same employee needs to be able to repeat multiple times within the audit table and still show the same id, which is causing my problems.同一个员工需要能够在审计表中重复多次并仍然显示相同的 id,这导致了我的问题。 I already tried substituting = for IN and using TOP 1 in my select statement but had no luck getting what I needed.我已经尝试用=代替IN并在我的 select 语句中使用TOP 1但没有运气得到我需要的东西。

The problem with your query is that the subquery is not correlated with the table being updated, hence it generates multiple records.您查询的问题是,子查询不相关用表进行更新,因此它会产生多个记录。

If there are no duplicates for (address, home_city, home_st) tuples in the Employee table, then you can use a simple correlated subquery:如果Employee表中的(address, home_city, home_st)元组没有重复项,那么您可以使用一个简单的相关子查询:

UPDATE AuditTable SET employee_id = (
    SELECT e.employee_id 
    FROM EmployeeTable e 
    WHERE 
        e.address = AuditTable.address 
        AND e.home_city = AuditTable.home_city 
        AND e.home_st = AuditTable.home_st
)

If duplicates may happen, then you can use TOP 1 or an aggregate function such as MAX() :如果可能发生重复,那么您可以使用TOP 1或聚合函数,例如MAX()

UPDATE AuditTable SET employee_id = (
    SELECT TOP 1 e.employee_id 
    FROM EmployeeTable e 
    WHERE 
        e.address = AuditTable.address 
        AND e.home_city = AuditTable.home_city 
        AND e.home_st = AuditTable.home_st
)

Use a join:使用连接:

UPDATE a
SET a.employee_id = e.employee_id
FROM AuditTable a INNER JOIN EmployeeTable e 
ON e.address = a.address AND e.home_city = a.home_city AND e.home_st = a.home_st

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM