Momen Zalabany
Momen Zalabany

Reputation: 9007

mysql duplicate check on 2 columns together

Table

|ID|owner|page|value|
|1 |0001 |home|demo |
|2 |0003 |home|demo |
|3 |0001 |home|demo |

what i want is to prevent owner to set 2 values for same page.

so my current approch was

|ID|owner|page|value|unique_check
|1 |0001 |home|demo |0001_home
|2 |0003 |home|demo |0003_home
unique_check is (unique key).

and now when ever im inserting into this table on php side i set unique_check = owner_page and since unique_check is a unique column mysql give an error and do not insert if that owner already did set value for this page.

but my question is , is there a way to do this on mysql only without php help or without extra 'unique_check' column ? (set unique to 2 columns together)

if there is no way to set unique-constrain to 2 columns, can i set unique_check default value = owner_page , so i wouldnt worry about doing that from php ?

Upvotes: 0

Views: 86

Answers (1)

John Woo
John Woo

Reputation: 263723

yes, add UNIQUE constraint,

ALTER TABLE tableNAME ADD CONSTRAINT tb_UQ UNIQUE (owner, page)

Upvotes: 3

Related Questions