CreatetableRoom_allotment(IdInt,NameVarchar(20),RoomNoInt);QueryOK,0rowsaffected(0.20sec)mysql>DescribeRoom_allotment;+--------+---- ---------+------+-----+-----"/> CreatetableRoom_allotment(IdInt,NameVarchar(20),RoomNoInt);QueryOK,0rowsaffected(0.20sec)mysql>DescribeRoom_allotment;+--------+---- ---------+------+-----+-----">

Home  >  Article  >  Database  >  How can we set PRIMARY KEY on multiple columns of an existing MySQL table?

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

WBOY
WBOYforward
2023-09-11 10:29:151246browse

我们如何在现有 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)

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)

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!

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