bodruk
bodruk

Reputation: 3262

MySQL: Ignore insert if match two columns

I need a help with a PHP/MySQL issue. I have a table named users and other named relationships.

users
--------------
id (PK)
name
email
etc

relashionships
--------------
id (PK)
id_user (FK to users.id)
id_friend (FK to users.id)
rating

I'm trying to INSERT multiple relationships but I don't want duplicated entries. I want to ignore the current row if the row is duplicated. I can't use the IGNORE statement because the id_user and the id_friend columns aren't unique. A user/friend may have multiple relationship rows.

Any tip?

Upvotes: 0

Views: 834

Answers (2)

bodruk
bodruk

Reputation: 3262

Thanks amenadiel, I found that solution here and worked for me!

CREATE UNIQUE INDEX relation ON relationship (id_user, id_friend)

Upvotes: 1

ffflabs
ffflabs

Reputation: 17481

You can create a unique key on the id_user/id_friend tuple. Neither of them are unique, but their combination is.

See multiple column indexes on the documentation.

Upvotes: 1

Related Questions