In mysql, you can make the field value unique by adding a unique constraint (Unique Key) to the field using the ALTER TABLE statement. The syntax is "ALTER TABLE data table name ADD CONSTRAINT unique constraint name UNIQUE (field name); ". The ALTER TABLE statement is used to modify the structure of the original table; the unique constraint can ensure the uniqueness of the field so that the value of the field cannot be repeated in all records.
The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.
In mysql, if you want to make a field unique, you can add a unique constraint to the field.
The unique constraint (Unique Key) means that the values of the fields in all records cannot be repeated, which can ensure the uniqueness of the fields. For example, after adding a unique constraint to the id field, the id value of each record is unique and cannot be repeated. If the id value of one of the records is '0001', then there cannot be another record with the id value of '0001' in the table.
There are two statements to add unique constraints to fields:
CREATE TABLE statement
ALTER TABLE statement
But the CREATE TABLE statement is set when creating the table and does not meet the requirements; therefore, the ALTER TABLE statement is used here. Syntax:
ALTER TABLE 数据表名 ADD CONSTRAINT 唯一约束名 UNIQUE(字段名);
Example: Modify the name field in the data table tb_dept to be unique
Let’s take a look at the table structure first:
DESC tb_dept;
Specify the department The name is unique
ALTER TABLE tb_dept ADD CONSTRAINT unique_name UNIQUE(name);
ok, the setting is completed. Look at the table structure again:
Description:
Unique constraints are similar to primary key constraints in that they can ensure the uniqueness of columns sex. The difference is that there can be multiple unique constraints in a table, and the column where the unique constraint is set is allowed to have null values, but there can only be one null value. There can only be one primary key constraint in a table, and no null values are allowed. For example, in the user information table, in order to avoid duplicate user names in the table, the user name can be set as a unique constraint.
[Related recommendations:mysql video tutorial]
The above is the detailed content of How to modify the unique field value in mysql. For more information, please follow other related articles on the PHP Chinese website!