The methods to set a composite primary key in MySQL are: specify or use the ALTER TABLE statement when creating a table, which is used to uniquely identify each row and improve query performance and data integrity. Advantages include finding rows quickly, enforcing uniqueness, and maintaining uniqueness across multiple columns, but the disadvantages are increased storage overhead and performance impact.
Set a composite primary key in MySQL
The composite primary key is a unique index containing multiple columns, which is used to Uniquely identifies each row in the table. It is often used to create more unique indexes to improve query performance and data integrity.
How to set the composite primary key:
<code class="sql">CREATE TABLE table_name ( column1 datatype, column2 datatype, PRIMARY KEY (column1, column2) );</code>
<code class="sql">ALTER TABLE table_name ADD PRIMARY KEY (column1, column2);</code>
Example:
Create a table named customers
, where The first_name
and last_name
columns constitute the composite primary key:
<code class="sql">CREATE TABLE customers ( customer_id INT NOT NULL AUTO_INCREMENT, first_name VARCHAR(255) NOT NULL, last_name VARCHAR(255) NOT NULL, PRIMARY KEY (first_name, last_name) );</code>
Advantages:
Limitations:
The above is the detailed content of How to set composite primary key in mysql. For more information, please follow other related articles on the PHP Chinese website!