【问题标题】:SQL merge statement with Joins带有连接的 SQL 合并语句
【发布时间】:2021-06-21 20:41:46
【问题描述】:

我正在尝试使用合并语句进行 upsert 操作。我想做类似下面的事情,我将目标表和源表都加入到学生表中,以获得只存在于学生表中的唯一键。请记住,我不能加入 StudentID。我的代码中可能有重复项。为了唯一性,我需要加入 schoolID。

Merge into GuardianTo gto inner join StudentTo sto on gto.fkStudentId = sto.StudentID
Using (Select * from GuardianFrom gfrom inner join StudentFrom sfrom on gfrom.fkStudentId = sfrom.StudentID) from
ON gto.guardianId = from.guardianId and sto.SchoolID = from.SchoolID
When....

我需要将目标 GuardianTo 表与 studentTo 表连接起来以获取 SchoolID 的唯一键。并将此 ID 与 From 表匹配。我知道这可以在单独的插入和更新语句中完成(不是合并),但是有没有办法使用合并语句来做类似上面的事情?

【问题讨论】:

    标签: sql merge sql-merge


    【解决方案1】:

    如果您使用的是 MSSQL,您可以像下面的代码一样进行合并。您需要提供要从源查询中使用的列名列表,然后在目标表 (GuardianTo) 中更新/插入您需要的列。

    Merge into GuardianTo gto 
    Using (Select * from GuardianFrom gfrom inner join StudentFrom sfrom on gfrom.fkStudentId = sfrom.StudentID ) AS source (<column names in GuardianFrom, Studentfrom go here> )
    ON (gto.guardianId = source.guardianId and gto.SchoolID = source.SchoolID)        
    WHEN MATCHED THEN          
    UPDATE SET <column in GuardianTo>= source.<column from source above> /* add any additional columns to update here*/
    WHEN NOT MATCHED THEN            
    INSERT (guardianId, SchoolID, StudentID /* add any additional columns to insert here*/)            
    VALUES (source.guardianId, source.SchoolID, source.StudentID /* add any additional columns from the source to insert here*/);
    

    【讨论】:

    • 感谢您的评论。但是,我的问题是 GuardianTo 表没有 schoolID。它需要加入 Student 表才能获得 SchoolID。我需要 GuardianFrom 表和 GuardianTo 表与 Student 表连接以检索 SchoolID 并匹配它们。基本上,代码行 3 中的 gto.SchoolID 不存在。它需要加入学生表来检索值。
    • 好的,但是您说您可以使用单独的插入和更新语句完成工作。只需更改 USING/ON 子句中所需的任何内容,即可将 GuardianTo 表中的行与其他两个表匹配。如有必要,您可以在 using 子句中再次添加 Student 表。只要您可以使用这些表编写 SQL 来找出何时更新以及何时插入,您就可以使用合并。但是,您可能会发现与插入/更新相比,合并的性能更差。根据用例,它也可能更容易分成插入/更新。
    • 我需要查看表定义和一些示例数据,以便能够帮助准确地找到所需的 SQL。
    猜你喜欢
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    相关资源
    最近更新 更多