This article introduces how to set the primary key in MySQL. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
The primary key is called a primary key constraint, which is a constraint often used in databases. In order to facilitate data search, a primary key will be added to each table.
Constraints on the primary key:
The value of the primary key cannot be empty
The primary key should be Clear and single
For the efficiency of query and processing, the primary key is generally set on an integer
Since the data needs to be queried, the primary key cannot be the same , so we will use it with the auto_increment
(auto-increment) attribute
There is only one primary key in a data table, and there cannot be multiple primary keys
Set the primary key when creating the table
create table 表名(字段名称 类型 primary key(字段名称));
Among them:
Table name: Yes The name of the data table to be operated;
Field name: is the field we need to create;
#Type: the type of data table field that needs to be operated ;
mysql> create table cmcc (id int,name varchar(25),primary key (id)); Query OK, 0 rows affected mysql> desc cmcc; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | varchar(25) | YES | | NULL | | +-------+-------------+------+-----+---------+-------+ 2 rows in set
This will set the primary key.
Set the primary key when modifying the table
alter table 表名 add primary key(字段);
If you forget to set the primary key when creating the data table, you can set it when modifying the table. (ps: I have deleted the primary key set during creation before modifying the table to set the primary key. There is no problem of multiple primary keys in one data table)
mysql> alter table cmcc add primary key(name); Query OK, 0 rows affected Records: 0 Duplicates: 0 Warnings: 0 mysql> desc cmcc; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | id | int(11) | NO | | NULL | | | name | varchar(25) | NO | PRI | NULL | | +-------+-------------+------+-----+---------+-------+ 2 rows in set
Related free learning recommendations: mysql Video tutorial
The above is the detailed content of Two ways to set primary key in mysql. For more information, please follow other related articles on the PHP Chinese website!