1

I wasn't sure how to explain this in the title, but what I have is a table like this:

user_id           | subscription_id
6                   12
6                   10
12                  6
4                   12

Each user can subscribe to all other users, but is it possible to prevent a user from subscribing to another user twice through a INSERT query?

As my subscription_id is not unique, this happens:

user_id           | subscription_id
6                   12
6                   12

And I want to avoid that. As far as I know INSERT IGNORE, INSERT UPDATE and ON DUPLICATE only works with unique keys.

Alex
  • 63
  • 2
  • 5
  • They work on unique and primary keys actually; not sure about triggers. Bottom line, spanning primary key :) – Ja͢ck Dec 06 '12 at 14:39

2 Answers2

0

You need to set up your database table to have a composite primary key for user_id AND subscription_id

That way each row has to be unique across both the columns.

See: How to properly create composite primary keys - MYSQL

Community
  • 1
  • 1
cowls
  • 24,013
  • 8
  • 48
  • 78
0

The only reliable and easy way to make sure that a tuple cannot occur more than once inside a single table is either:

  1. Use a spanning unique key

  2. Use a spanning primary key

  3. Maybe triggers

The first two are roughly the same, but unique keys treat null values as distinct as well, so that might not work for you.

ALTER TABLE user_subscriptions ADD PRIMARY(user_id, subscription_id);
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309