954,560 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Avoid the duplicate primary keys

Hi all, I need your help.

I have an insert query which insert a few rows into the table A.
TableA has two primary keys, which are fieldA and fieldB.

The SQL is written as follows:

INSERT INTO TableA (fieldA , fieldB, fieldC, fieldD)
SELECT DISTINCTROW TableB.fieldA, TableB.fieldB, TableB.fieldC, TableB.fieldD FROM TableB

The problem is that SELECT statement from TableB produces a duplicate combination of fieldA and fieldB. for example.

fieldA fieldB fieldC fieldD
1 1 3 4
1 1 2 5
1 2 5 6

Therefore I have an error when I try to run this insert statement.
What should I do to avoid this to happen?
I just want one row for any duplicate primary keys and I am not fussy. I just don't want this error to pop up.

the result that I desire will be something like

fieldA fieldB fieldC fieldD
1 1 3 4
1 2 5 6

Thank you so much, I really appreciate your help.

neosonic
Junior Poster
137 posts since Nov 2009
Reputation Points: 22
Solved Threads: 1
 

How mysql server will know what to select out of multiple choices,
1134
1125

What is criteria of selection. what is the version of mssql

urtrivedi
Nearly a Posting Virtuoso
1,306 posts since Dec 2008
Reputation Points: 257
Solved Threads: 270
 

You can do a group by on fieldA and fieldB.

pritaeas
Posting Expert
Moderator
5,480 posts since Jul 2006
Reputation Points: 653
Solved Threads: 875
 

You could always add another key column (fieldC) to TableA. If you're getting duplicates, then your normalization is incomplete and your TableA can't uniquely represent the data you need to store.

Or you could cheat and create another column as primary key that is an identity column, and take fieldA and fieldB out of the primary key altogether.
(;) Being the DBA means never having to say you're sorry.)

BitBlt
Master Poster
711 posts since Feb 2011
Reputation Points: 367
Solved Threads: 109
 

Hi... thanks for all the reply.
@Pritaeas thanks for your idea.

I can do it with following sql:

INSERT INTO TableA (fieldA , fieldB, fieldC, fieldD)
SELECT DISTINCTROW min(TableB.fieldA), min(TableB.fieldB), min(TableB.fieldC), min(TableB.fieldD) FROM TableB
GROUP BY TableB.fieldA, TableB.fieldB

neosonic
Junior Poster
137 posts since Nov 2009
Reputation Points: 22
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: