How to set the primary key in mysql
In this issue, the editor will bring you about how to set the primary key in mysql. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
The primary key is called the primary key constraint, which is often used in the database. To make it easier to find data, a primary key is added to each table.
Constraints for primary keys:
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 integers
Because the data needs to be queried, the primary key cannot be the same, so we will use it in conjunction with the auto_increment attribute
There is only one primary key in a data table, not multiple primary keys.
Set the primary key when you create the table
Create table table name (field name type primary key (field name))
Where:
Table name: is the name of the data table of the operation
Field name: is the field we need to create
Type: the type of datasheet field that needs to be operated
Mysql > create table cmcc (id int,name varchar (25), primary key (id)); Query OK, 0 rows affectedmysql > desc cmcc +-+ | Field | Type | Null | Key | Default | Extra | +-+- -+ | id | int (11) | NO | PRI | NULL | name | varchar (25) | YES | | NULL | | +-+-+ 2 rows in set
This sets the primary key.
Set the primary key when you modify the table
Alter table table name add primary key (field)
If you forget to set the primary key when you create the data table, you can do so when you modify the table. (ps: I deleted the primary key set at creation time before I modified the table to set the primary key. There is no problem that there are multiple primary keys in a data table.)
Mysql > alter table cmcc add primary key (name); Query OK, 0 rows affectedRecords: 0 Duplicates: 0 Warnings: 0mysql > desc cmcc +-+ | Field | Type | Null | Key | Default | Extra | +-+- -+ | id | int (11) | NO | | NULL | | name | varchar (25) | NO | PRI | NULL | | +-+-+ 2 rows in set above is how to set the primary key in mysql. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.