SoFunction
Updated on 2025-03-04

How to operate joint primary keys in MySQL

MySQL joint primary key operation

In MySQL, creating a table containing a joint primary key is a common requirement, especially when multiple fields need to jointly identify a record.

1. Create a joint primary key

Define the joint primary key while creating the table, usePRIMARY KEYKeywords specify multiple fields as primary keys.

For example:

CREATE TABLE orders (
    order_id INT,
    customer_id INT,
    order_date DATE,
    PRIMARY KEY (order_id, customer_id)
);

2. Added joint primary key

If the table already exists

Can be passedALTER TABLEAdd a joint primary key in the statement

ALTER TABLE orders ADD PRIMARY KEY (order_id, customer_id);

3. Modify the joint primary key

If you need to modify the joint primary key of the table, you can first delete the old primary key and then add the new primary key

ALTER TABLE orders DROP PRIMARY KEY;
ALTER TABLE orders ADD PRIMARY KEY (new_column1, new_column2);

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.