如何将唯一键添加到现有表(具有非唯一行)?
您可以借助alter命令将唯一键添加到现有表。语法如下-
ALTER TABLE yourTableName ADD CONSTRAINT yourConstraintName UNIQUE(yourColumnName1,yourColumnName2,............N);
为了理解上述概念,让我们创建一个包含一些列的表。创建表的查询-
mysql> create table MovieCollectionDemo −> ( −> MovieId int, −> MovieDirectorName varchar(200), −> NumberOfSongs int unsigned −> );
现在您可以检查表是否没有任何唯一约束。检查唯一约束的查询如下-
mysql> desc MovieCollectionDemo;
以下是输出-
+-------------------+------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------------+------------------+------+-----+---------+-------+ | MovieId | int(11) | YES | | NULL | | | MovieDirectorName | varchar(200) | YES | | NULL | | | NumberOfSongs | int(10) unsigned | YES | | NULL | | +-------------------+------------------+------+-----+---------+-------+ 3 rows in set (0.00 sec)
现在,您可以根据上述语法添加唯一键。我们在MovieId列上添加了唯一键。查询如下-
mysql> alter table MovieCollectionDemo add constraint uni_moviecollectio unique(MovieId); Records: 0 Duplicates: 0 Warnings: 0
让我们查看整个表和MovieId列以检查其是否具有唯一键。
mysql> desc MovieCollectionDemo;
以下是输出-
+-------------------+------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------------+------------------+------+-----+---------+-------+ | MovieId | int(11) | YES | UNI | NULL | | | MovieDirectorName | varchar(200) | YES | | NULL | | | NumberOfSongs | int(10) unsigned | YES | | NULL | | +-------------------+------------------+------+-----+---------+-------+ 3 rows in set (0.02 sec)
上面的输出显示“UNI”,这意味着“MovieId”字段具有唯一键。