How to insert Distinct Records from Table A to Table B (both tables have same structure)

依然范特西╮ 提交于 2019-11-30 21:22:23
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

If by DISTINCT you mean unique records that are on TableB that aren't already in TableA, then do the following:

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
INSERT INTO TableB
    (Col1, Col2, ...)
    SELECT DISTINCT Col1, Col2, ...
        FROM TableA
    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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!