如何在 MySQL 表的多个列上设置 PRIMARY KEY?
mysqlmysqli database
实际上,MySQL 允许我们在多个列上设置 PRIMARY KEY。这样做的好处是,我们可以将多个列作为一个实体来处理。
示例
我们通过在多个列上定义复合 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'