0

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.

4
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by neosonic
0

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

Edited by urtrivedi: n/a

0

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.)

Edited by BitBlt: n/a

0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.