如何为现有表(带非唯一行)添加唯一键?
借助 alter 命令,你可以为现有表添加唯一键。语法如下 −
ALTER TABLE yourTableName ADD CONSTRAINT yourConstraintName UNIQUE(yourColumnName1,yourColumnName2,............N);
为了理解上述概念,让我们创建一个包含一些列的表。创建表的查询 −
mysql> create table MovieCollectionDemo −> ( −> MovieId int, −> MovieDirectorName varchar(200), −> NumberOfSongs int unsigned −> ); Query OK, 0 rows affected (0.62 sec)
现在,你可以检查该表是否具有任何唯一约束。检查唯一约束的查询如下 −
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); Query OK, 0 rows affected (0.46 sec) 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”字段具有唯一键。
广告