How to avoid getting error "duplicate entry '1' for key primary" when inserting one table into another?

298 Views Asked by At
INSERT INTO tableA (SELECT * FROM tableB);

creates an error

"Duplicate entry '1' for key Primary".

tableA has field "Lid" which is primary, auto-increment and causing the error.

tableB has a set of records with identical fields to tableA. Field Lid is numbered 1-40.

I need ALL records from tableB to be appended to tableA every time a new user logs in to my system. Once copied to TableA, the records are updated with that users UserID. When tableB is appended to tableA, field tableA.Lid should autoincrement, not take the duplicate value from tableB.

The following works but I want to avoid specifying field names in code:

INSERT INTO tableA (field2, field3,...) SELECT field2, field3, ... FROM tableB

I skip field1 which is the "Lid" primary auto-increment field.

If I set tableB.Lid to null would this work?

I want to use INSERT INTO tableA (SELECT * FROM tableB) as this avoids specifying field names in code.

1

There are 1 best solutions below

0
Pick Avana On

In tableB i changed field "Lid" to just be a regular INT field, not indexed, not primary, not auto-increment, default to Null. I am now able to "INSERT INTO tableA SELECT * FROM tableB" and all records in tableA are auto-incrementing correctly. As mentioned I preferred not to use field names in code so wanted to keep solution "generic".