实际上,MySQL允许我们在多个列上设置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'
以上是如何在 MySQL 表的多个列上设置 PRIMARY KEY?的详细内容。更多信息请关注PHP中文网其他相关文章!