Home > Database > Mysql Tutorial > body text

How can we set PRIMARY KEY on multiple columns of an existing MySQL table?

WBOY
Release: 2023-09-11 10:29:15
forward
1247 people have browsed it

我们如何在现有 MySQL 表的多个列上设置 PRIMARY KEY?

We can set PRIMARY KEY constraints on multiple columns of an existing table by using the ADD keyword and the ALTER TABLE statement.

Example

Suppose we have a table "Room_allotment" as follows -

mysql> Create table Room_allotment(Id Int, Name Varchar(20), RoomNo Int);
Query OK, 0 rows affected (0.20 sec)

mysql> Describe Room_allotment;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Id     | int(11)     | YES  |     | NULL    |       |
| Name   | varchar(20) | YES  |     | NULL    |       |
| RoomNo | int(11)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.11 sec)
Copy after login

Now we can add compound on multiple columns "id" and "Name" using the following query Primary key

mysql> Alter Table Room_allotment ADD PRIMARY KEY(Id, Name);
Query OK, 0 rows affected (0.29 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> Describe Room_allotment;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Id     | int(11)     | NO   | PRI | 0       |       |
| Name   | varchar(20) | NO   | PRI |         |       |
| RoomNo | int(11)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.12 sec)
Copy after login

As can be seen from the above result set, PRIMARY KEY has been added to multiple columns.

The above is the detailed content of How can we set PRIMARY KEY on multiple columns of an existing 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