Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to insert only Distinct Records from Table "A" to Table "B". Assume both the tables has same structure.

like image 669
Ramesh Avatar asked Mar 02 '11 17:03

Ramesh


People also ask

How do I insert unique records from one table to another?

INSERT DISTINCT Records INTO New Tables In order to copy data from an existing table to a new one, you can use the "INSERT INTO SELECT DISTINCT" pattern. After "INSERT INTO", you specify the target table's name - organizations in the below case.

How do I insert two tables at the same time?

The T-SQL function OUTPUT, which was introduced in 2005, can be used to insert multiple values into multiple tables in a single statement. The output values of each row that was part of an INSERT, UPDATE or DELETE operation are returned by the OUTPUT clause.

How do I insert without duplicates in SQL?

Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.


2 Answers

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
like image 187
Lamak Avatar answered Oct 08 '22 01:10

Lamak


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

like image 30
TheJubilex Avatar answered Oct 07 '22 23:10

TheJubilex