【问题标题】:Query pairs of attributes over tables in SQL Server在 SQL Server 中的表上查询属性对
【发布时间】:2017-08-11 10:01:01
【问题描述】:

我有两个具有以下架构的表

表 A:

(Id(int PK),EmployeeId(int),DepartmentId(int))

表 B:

(Id(int PK),EmployeeId(int),DepartmentId(int))

DepartmentId,EmployeeId 具有 1 对 1 映射,即它们创建一个唯一的对, 我在表 B 中有一些无效的部门 ID 映射,EmployeeId 我想从表 B 中查询所有这些 Id,其中表 A 中的相同 EmployeeId 在表 B 中具有不同的部门 ID。

【问题讨论】:

    标签: sql sql-server database


    【解决方案1】:

    试试这样的

    select * 
    from tableb b 
    Where exists (select 1 from tablea a 
                  where a.EmployeeId = b.EmployeeId 
                  and a.DepartmentId <> b.DepartmentId)
    

    编辑:更新

    UPDATE b
    SET    b.DepartmentId = a.DepartmentId
    FROM   tablea a
           INNER JOIN tableb b
                   ON a.EmployeeId = b.EmployeeId
    WHERE  a.DepartmentId != b.DepartmentId 
    

    【讨论】:

    • 非常感谢,您能否建议一个 SQL,通过从表 A 中获取正确的部门 ID 来更新表 B 中的坏部门 ID
    【解决方案2】:
    select b.EmployeeId
    from a
    inner join b on a.EmployeeId = b.EmployeeId
    where a.DepartmentId != b.DepartmentId
    

    【讨论】:

    • 非常感谢,您能否建议一个 SQL,通过从表 A 中获取正确的部门 ID 来更新表 B 中的坏部门 ID
    • UPDATE b SET DepartmentId = a.DepartmentId FROM a INNER JOIN b ON a.EmployeeId = b.EmployeeId WHERE a.DepartmentId != b.DepartmentId
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 2012-10-06
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多