如何在 MySQL 表格的多栏上设置 PRIMARY KEY?
实际上,MySQL 允许我们在多栏上设置 PRIMARY KEY。这样做的优势在于,我们可以将多栏作为单个实体来操作。
示例
我们已经创建了 allotment 表格,方法是在多栏上定义复合 PRIMARY KEY,如下所示 −
mysql> Create table allotment( RollNo Int, Name Varchar(20), RoomNo Int, PRIMARY KEY(RollNo, RoomNo)); Query OK, 0 rows affected (0.23 sec) mysql> Describe allotment; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | RollNo | int(11) | NO | PRI | 0 | | | Name | varchar(20) | YES | | NULL | | | RoomNo | int(11) | NO | PRI | 0 | | +--------+-------------+------+-----+---------+-------+ 3 rows in set (0.10 sec)
现在,当我们尝试在两栏中插入重复复合值时,MySQL 就会抛出一个错误,如下所示 −
mysql> Insert Into allotment values(1, 'Aarav', 201),(2,'Harshit',201),(1,'Rahul ',201); ERROR 1062 (23000): Duplicate entry '1-201' for key 'PRIMARY'
广告