tags:

views:

18

answers:

1

Is the proper way to use the UNIQUE KEY in my MySQL table?

MySQL data.

id  pid aid
1   2   3
2   3   2
3   3   4   

MySQL table.

CREATE TABLE ab ( 
id INT UNSIGNED NOT NULL AUTO_INCREMENT, 
pid INT UNSIGNED NOT NULL DEFAULT 0, 
aid INT UNSIGNED NOT NULL DEFAULT 0,  
PRIMARY KEY (id), 
UNIQUE KEY (pid, aid)
);
+1  A: 

The unique index you have created is a valid index. It creates an index which allows duplicate values in pid and also in aid but does not allow duplicates of any pair (pid, aid). For example, this insert would fail if your table already contains the data from your example because it conflicts with the second row:

INSERT INTO ab (pid, aid) VALUES (3, 2)
Mark Byers
if i have the number 3 for both pid and aid is that valid?
slang
@sland: Yes that is valid.
Mark Byers
can I have both aid and pid with the same values only once on the same row to be clear.
slang
@slang: Yes, you can try `INSERT INTO ab (pid, aid) VALUES (3, 3)`. This will work the first time - but if you try it twice it will fail the second time.
Mark Byers
Thanks for the help Mark Byers
slang