我有两个数据库
Test1
Test2
并且我在每个数据库中都有 Author
表,我想将 AuthorId
从 Test1
同步到 Test2
.
在 Test2
中还有另一个表 ProductAuthor
,它在 Author 表中对 AuthorID 有 f外键约束
。
我现在正在做的是
去掉外键约束
更新两个表:Author 和 ProductAuthor
添加外键约束
--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])
上面的脚本将 特定的 AuthorId 从 Test1.Author 更新为 Test2.Author 和 Test2.ProductAuthor
提问:
我将如何更改脚本,以便它根据 Test1.Author 中的名字和姓氏更新 Test2.Author 和 Test2.ProductAuthor 中的所有行?
最佳答案
我认为您要做的是更新并选择此处找到的内容:
How to do 3 table JOIN in UPDATE query?
你可能只需要做一个基本的连接——即
JOIN (SELECT * FROM db1.author WHERE ....) as db1
SET db2.author = db1.ID
尝试一下,看看它是否有效。
关于mysql - 将表的键字段从一个数据库同步到另一个数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37696944/