How to set up two primary keys in MySQL
A primary key is a column or combination of columns that uniquely identifies each row in a table. Generally, a table can only have one primary key, but in some special cases, two primary keys are allowed.
Steps:
Use composite primary key:
Using composite primary key is to set two primary keys recommended method. A composite primary key is composed of two or more columns, and the value of each column must be unique.
<code class="sql">ALTER TABLE table_name ADD PRIMARY KEY (column1, column2);</code>
For example, to set a composite primary key for the customer_id
and last_name
columns in the customers
table:
<code class="sql">ALTER TABLE customers ADD PRIMARY KEY (customer_id, last_name);</code>
Using multi-column primary keys:
Multi-column primary keys are similar to composite primary keys, but they are specified using special syntax.
<code class="sql">ALTER TABLE table_name ADD PRIMARY KEY USING INDEX (index_name);</code>
where index_name
is the name of an existing unique index.
For example, suppose the customers
table has a unique index named customer_index
, which can be used as the primary key:
<code class="sql">ALTER TABLE customers ADD PRIMARY KEY USING INDEX (customer_index);</code>
It should be noted that , multi-column primary keys are not available in some MySQL versions.
Advantages and disadvantages:
Advantages of composite primary keys:
Disadvantages of composite primary keys:
Advantages of multi-column primary keys:
##Disadvantages of multi-column primary keys:
The above is the detailed content of How to set two primary keys in mysql. For more information, please follow other related articles on the PHP Chinese website!