tags:

views:

37

answers:

2

I am creating a table ,in the table two column is unique, I mean columnA and columnB do not have same value: such as :

Table X
A B
1 2(RIGHT,unique)
2 2(RIGHT, unique)
1 3(RIGHT, not unique)
2 3(RIGHT, not unique)
1 2 (WRONG, not unique)

How to create such a table? many thanks!

create table X 
(
[ID] INTEGER PRIMARY KEY AUTOINCREASE NOT NULL,\
[A] INTEGER,
[B] INTEGER);
+3  A: 

Create a unique key column:

CREATE TABLE X
(
    ID INTEGER PRIMARY KEY AUTOINCREASE NOT NULL,
    A INTEGER,
    B INTEGER,
    UNIQUE KEY(A, B)
);

INSERT INTO X(A, B) VALUES(1, 2);
INSERT INTO X(A, B) VALUES(2, 2);
INSERT INTO X(A, B) VALUES(1, 3);
INSERT INTO X(A, B) VALUES(2, 3);
INSERT INTO X(A, B) VALUES(1, 2);

The last line will fail because the combination a = 1 and b = 2 already exists in the table.

In silico
Many Thanks, however I already has a primary key
sxingfeng
I add it in my question
sxingfeng
Edited. Create a unique key instead.
In silico
+2  A: 
CREATE UNIQUE INDEX `my_index_name` ON `my_table` (`col1`,`col2`)
zed_0xff
Thanks zed! I see
sxingfeng