SQL 如何将表 A 中的不同记录插入到表 B(两个表具有相同的结构)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5171328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert Distinct Records from Table A to Table B (both tables have same structure)
提问by Ramesh
I want to insert only Distinct Records from Table "A" to Table "B". Assume both the tables has same structure.
我只想将表“A”中的不同记录插入到表“B”。假设两个表具有相同的结构。
回答by TheJubilex
INSERT INTO B SELECT DISTINCT * FROM A
You might not want the id column of the table to be part of the distinct check, so use this solution if that's the case: https://stackoverflow.com/a/5171345/453673
您可能不希望表的 id 列成为不同检查的一部分,因此如果是这种情况,请使用此解决方案:https: //stackoverflow.com/a/5171345/453673
回答by Lamak
If by DISTINCT
you mean unique records that are on TableB that aren't already in TableA, then do the following:
如果DISTINCT
您的意思是 TableB 上尚未存在于 TableA 中的唯一记录,请执行以下操作:
INSERT INTO TableB(Col1, Col2, Col3, ... , Coln)
SELECT DISTINCT A.Col1, A.Col2, A.Col3, ... , A.Coln
FROM TableA A
LEFT JOIN TableB B
ON A.KeyOfTableA = B.KeyOfTableB
WHERE B.KeyOfTableB IS NULL
回答by Joe Stefanelli
INSERT INTO TableB
(Col1, Col2, ...)
SELECT DISTINCT Col1, Col2, ...
FROM TableA
回答by Alexander Brattsev
INSERT INTO TableB
SELECT *
FROM TableA AS A
WHERE NOT EXISTS(SELECT * FROM TableB AS B WHERE B.Field1 = A.Field1)
-- If need: B.Field2 = A.Field2 and B.Field3 = A.Field3