为了使组合键具有唯一性,您需要使用ADD UNIQUE命令。以下是语法-
alter table yourTableName add unique yourUniqueName( yourColumnName1,yourColumnName2,.......N);
让我们首先创建一个表。以下是查询-
mysql> create table makeCompositeKeyDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(40), -> StudentAge int, -> StudentGrade char(1) -> );
现在使用DESC命令检查表的描述。以下是查询-
mysql> desc makeCompositeKeyDemo;
这将产生以下输出-
+--------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+-------------+------+-----+---------+----------------+ | Id | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(40) | YES | | NULL | | | StudentAge | int(11) | YES | | NULL | | | StudentGrade | char(1) | YES | | NULL | | +--------------+-------------+------+-----+---------+----------------+ 4 rows in set (1.65 sec)
以下是形成唯一的组合键的查询-
mysql> alter table makeCompositeKeyDemo add unique Name_Age_Grade( StudentName,StudentAge,StudentGrade); Records: 0 Duplicates: 0 Warnings: 0
现在再次检查表说明。以下是查询-
mysql> desc makeCompositeKeyDemo;
这将产生以下输出-
+--------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+-------------+------+-----+---------+----------------+ | Id | int(11) | NO | PRI | NULL | auto_increment | | StudentName | varchar(40) | YES | MUL | NULL | | | StudentAge | int(11) | YES | | NULL | | | StudentGrade | char(1) | YES | | NULL | | +--------------+-------------+------+-----+---------+----------------+ 4 rows in set (0.00 sec)