Home > Database > Mysql Tutorial > 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
Release: 2023-08-29 11:37:02
forward
1414 people have browsed it

如何在 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)
Copy after login

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'
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template