简体   繁体   中英

SQL multiple unique columns

Is it possible to use unique on multiple columns?

like:

 user_vote user_id 
 ------------------
      1         1
      1         2
      2         1 

both unique

This must be possible

But:

  user_vote user_id
     1         2
     1         2 

This must not be possible

You can add a unique constraint on the column's combination:

ALTER TABLE my_table
ADD CONSTRAINT my_table_uq UNIQUE (user_vote, user_id)

MySQL / SQL Server / Oracle / MS Access:

 CREATE TABLE uservotetable
 (
   user_vote int NOT NULL,
   user_id int NOT NULL,
 CONSTRAINT uservote UNIQUE (user_vote ,user_id)
  );

and if you created your table before ..then you can use ALTER

  ALTER TABLE uservotetable
  ADD CONSTRAINT uservote UNIQUE (user_vote ,user_id)

this can be useful for you sql_unique

You need to define a composite unique constraint.

SQL Server, One way to do that in SQL Server is by adding UNIQUE INDEX

ALTER TABLE table_name ADD UNIQUE INDEX (User_Vote, User_Id);

In Oracle,

ALTER TABLE table_name
ADD CONSTRAINT uc_1 UNIQUE (User_Vote, User_Id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM