【问题标题】:Synchronising a table's key field from one database to another将表的键字段从一个数据库同步到另一个数据库
【发布时间】:2016-10-08 09:27:02
【问题描述】:

我有 2 个数据库

Test1

Test2

我在每个数据库中都有Author 表,我想将AuthorIdTest1 同步到Test2

Test2 中还有另一个表ProductAuthor,其中包含foreign Key constraint on AuthorID in Author table

我现在正在做的是

  1. 删除外键约束

  2. 更新两个表:Author 和 ProductAuthor

  3. 添加外键约束

     --remove the foreign key constraint
    
    ALTER TABLE [dbo].[ProductAuthor] DROP CONSTRAINT [FK_ProductAuthor_Author]
    
    Update Test2.dbo.ProductAuthor set AuthorId = (
    select distinct T1A.AuthorId from Test1.dbo.Author T1A 
    INNER JOIN Test2.dbo.Author T2A ON T1A.FirstName =  T2A.firstname COLLATE Latin1_General_CI_AS and T1A.LastName =  T2A.surname COLLATE Latin1_General_CI_AS
    where T2A.AuthorId = ProductAuthor.AuthorId
    ) where ProductAuthor.AuthorId = 6793
    
    Update Test2.dbo.Author set AuthorId = (
    select Distinct T1A.AuthorId from Test1.dbo.Author T1A 
    INNER JOIN Test2.dbo.Author T2A ON T1A.FirstName =  T2A.firstname COLLATE Latin1_General_CI_AS and T1A.LastName =  T2A.surname COLLATE Latin1_General_CI_AS
    where T1A.AuthorId = 106793) where Test2.dbo.AuthorId = 6793
    
    
    --add the foreign key constraint
    ALTER TABLE [dbo].[ProductAuthor]  WITH NOCHECK ADD  CONSTRAINT [FK_ProductAuthor_Author] FOREIGN KEY([AuthorId])
    REFERENCES [dbo].[Author] ([AuthorId])
    

上面的脚本更新了specific AuthorId from Test1.Author to Test2.Author and Test2.ProductAuthor

问:
我将如何更改脚本,以便它根据 Test1.Author 中的名字和姓氏更新 Test2.Author 和 Test2.ProductAuthor 中的所有行?

【问题讨论】:

标签: mysql sql-server tsql


【解决方案1】:

我认为您要做的是更新并选择此处:

How to do 3 table JOIN in UPDATE query?

您可能只需要进行基本连接 - 即

JOIN (SELECT * FROM db1.author WHERE ....) as db1
SET db2.author = db1.ID

试试看它是否有效。

【讨论】:

  • 好问题 - 不太确定。不要用,我怕。但这被标记为 mysql,它应该这样做。
猜你喜欢
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多