實(shí)際上,MySQL允許我們?cè)诙鄠€(gè)列上設(shè)置PRIMARY KEY。這樣做的優(yōu)點(diǎn)是我們可以將多個(gè)列作為單個(gè)實(shí)體進(jìn)行處理。
示例
我們通過(guò)在多個(gè)列上定義復(fù)合主鍵來(lái)創(chuàng)建表分配,如下所示 –
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)
登錄后復(fù)制
現(xiàn)在,當(dāng)我們嘗試在兩列中插入重復(fù)的復(fù)合值時(shí),MySQL 會(huì)拋出如下錯(cuò)誤 –
mysql> Insert Into allotment values(1, 'Aarav', 201),(2,'Harshit',201),(1,'Rahul ',201); ERROR 1062 (23000): Duplicate entry '1-201' for key 'PRIMARY'
登錄后復(fù)制
以上就是如何在 MySQL 表的多個(gè)列上設(shè)置 PRIMARY KEY?的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.92cms.cn其它相關(guān)文章!