There are primary key constraints and unique key constraints in the constraints on columns in the mysql database. These two constraints are prone to confusion. Here are the differences between the two:
Comparison of primary key and unique key:
constraint | Guarantee uniqueness | Is it empty | How many in a table | Whether to allow combination |
Primary key | Yes | no | At most one | Yes (but not recommended) |
Unique key | Yes | Yes | Can be multiple | Yes (but not recommended) |
By the way, here are some notes about foreign keys:
1. It is required to set the foreign key relationship from the table
2. The type of the foreign key column of the slave table is consistent or compatible with the type of the associated column of the main table, and the name is not required.
3. The associated column in the main table must be a key (usually a primary key or a unique key)
4. When inserting data, insert the main table first, and then insert the slave table. When deleting data, delete the slave table first, and then delete the main table
Add constraints when modifying the table
1. Add column-level constraints
alter table table name modify column field name field type new constraint;
2. Add table-level constraints
alter table table name add [constarint constraint name] constraint type (field name) [foreign key reference references table (the main table field to be associated)]
Delete constraints when modifying the table
1. Delete column-level constraints
alter table table name modify column field name (remove the constraints to be deleted, and keep the rest)
2. Delete table-level constraints
alter table table name drop constraint name
Summary: the difference between column-level constraints and table-level constraints
Constraint name | position | Supported constraint types | Is it possible to name a constraint |
Column-level constraints: | Behind the column | The syntax is supported, but the foreign key has no effect | Can't |
Table-level constraints: | Below all columns | Default and non-empty are not supported, others are directly supported | Yes, the primary key has no effect |