How to add a primary key constraint in MySQL?
In MySQL, you can add a primary key constraint using the following method:
- “When creating tables, use the PRIMARY KEY keyword to specify the primary key. For example:”
CREATE TABLE 表名 (
列名1 数据类型,
列名2 数据类型,
...
PRIMARY KEY (列名1)
);
- You can use the ALTER TABLE statement to add a primary key constraint to an existing table. For example:
ALTER TABLE 表名
ADD PRIMARY KEY (列名1);
When executing the statement above, make sure that column1 already exists in the table.
- To create a composite primary key on multiple columns, you can use the following syntax:
CREATE TABLE 表名 (
列名1 数据类型,
列名2 数据类型,
...
PRIMARY KEY (列名1, 列名2)
);
In the example above, Column 1 and Column 2 will form a composite primary key.
Please note that the primary key values must be unique and not empty. Therefore, ensure that the column values meet these requirements before creating the primary key constraint.