eevaa
eevaa

Reputation: 1457

Insert row only if it doesn't exist already in MySQL

I have a table table with two columns (idA and idB). The table assigns Bs to As, like this:

    A  |  B
    1  |  4
    3  |  2
    3  |  4
    4  |  1
    4  |  3  ...

So one A can have multiple Bs and thus shows up in more than one row. Hence, the table cannot have a primary key and I cannot use a unique column.

Is there a way to insert new rows only if an equal value pairing does not already exist, all in one query?

I tried REPLACE INTO and INSERT IGNORE INTO as mentioned here, but both seem to work for tables with primary keys only.

Upvotes: 0

Views: 660

Answers (1)

juergen d
juergen d

Reputation: 204894

You can add a primary key! It just has to be over two columns and not just one.

ALTER TABLE your_table
ADD PRIMARY KEY(idA, idB)

That will make sure you only have unique records for both columns.

Upvotes: 1

Related Questions