Home  >  Article  >  Database  >  How to set PRIMARY KEY on multiple columns of a MySQL table?

How to set PRIMARY KEY on multiple columns of a MySQL table?

PHPz
PHPzforward
2023-08-29 11:37:021371browse

如何在 MySQL 表的多个列上设置 PRIMARY KEY?

Actually, MySQL allows us to set PRIMARY KEY on multiple columns. The advantage of this is that we can handle multiple columns as a single entity.

Example

We create a table distribution by defining a composite primary key on multiple columns as shown below -

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)

Now, when we try to insert duplicate compound values ​​in two columns, MySQL will throw the following error -

mysql> Insert Into allotment values(1, 'Aarav', 201),(2,'Harshit',201),(1,'Rahul ',201);
ERROR 1062 (23000): Duplicate entry '1-201' for key 'PRIMARY'

The above is the detailed content of How to set PRIMARY KEY on multiple columns of a MySQL table?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete