当前位置:网站首页>The concept, function, characteristics, creation and deletion of MySQL constraints
The concept, function, characteristics, creation and deletion of MySQL constraints
2022-07-02 01:46:00 【No development, no work】
List of articles
- 1 The role of constraints
- 2 How to add constraints
- 3 How to view constraints in a table
- 4 Constraint level
1 The role of constraints
1.1 Generalization
- not null( Non empty constraint )
- unique( Uniqueness constraint )
- primary key( Primary key constraint )
- foreign key( Foreign key constraints )
- check( Check constraint )
- default( Default constraint )
1.2 classification
1.2.1 Non empty constraint
1.2.1.1 effect
Limit a field / The value of a column cannot be empty
1.2.1.2 keyword
NOT NULL
1.2.1.3 characteristic
- By default, all types of values can be NULL
- Non empty constraints can only appear on columns of table objects , Only one column can be qualified as non empty , Cannot combine non empty
- A table can have many columns, which are limited to non empty
- An empty string " It's not equal to NULL,0 Also is not equal to NULL
1.2.1.4 Add non empty constraints
1.2.1.4.1 Add constraints when creating tables
CREATE TABLE test1 (
id INT NOT NULL,-- Add a non NULL constraint when creating a table
last_name VARCHAR ( 20 ) NOT NULL,-- Add a non NULL constraint when creating a table
email VARCHAR ( 25 ),
salary DECIMAL ( 10, 2 )
)
1.2.1.4.2 Add constraints when modifying tables
-- Add non empty constraints when modifying tables
ALTER TABLE test1 MODIFY email VARCHAR ( 25 ) NOT NULL;
1.2.1.5 Delete constraints
-- Delete non empty constraints when modifying tables
ALTER TABLE test1 MODIFY email VARCHAR ( 25 );
1.2.2 Uniqueness constraint
1.2.2.1 effect
Used to restrict a field / The value of a column cannot be repeated .
1.2.2.2 keyword
UNIQUE
1.2.2.3 characteristic
- The same table can have multiple unique constraints
- A unique constraint can be a unique value for a column , You can also combine multiple columns to have unique values
- The uniqueness constraint allows column values to be empty
- When creating unique constraints , If you don't name a unique constraint , The default is the same as the column name
- Mysql A unique index will be created by default for columns with unique constraints
1.2.2.4 Add unique constraints
1.2.2.4.1 Add constraints when creating tables
CREATE TABLE test2 (
-- Column level constraints
id INT UNIQUE,-- Add unique constraints when creating tables
last_name VARCHAR ( 20 ),
email VARCHAR ( 25 ),
salary DECIMAL ( 10, 2 ),
-- Table level constraints
CONSTRAINT uk_test2_email UNIQUE ( email )
)
-- The uniqueness constraint of composition ( Only when the two fields are the same can they conflict )
CREATE TABLE test3(
id INT,
last_name VARCHAR ( 20 ),
email VARCHAR ( 25 ),
salary DECIMAL ( 10, 2 ),
-- Table level constraints
CONSTRAINT uk_test2_id_email UNIQUE ( id,email )
)
1.2.2.4.2 Add constraints when modifying tables
-- Add unique constraints
-- Mode one
ALTER TABLE test2 ADD CONSTRAINT UNIQUE(last_name);
-- Add composite constraints
ALTER TABLE test3 ADD CONSTRAINT uk_test2_last_name_email UNIQUE(last_name,email);
-- Mode two
ALTER TABLE test2 MODIFY salary DECIMAL ( 10, 2 ) UNIQUE;
1.2.2.5 Delete constraints
ALTER TABLE < Table name > DROP INDEX < Unique constraint name >;
1.2.2.5.1 matters needing attention
- A unique index will also be automatically created on the column to which the uniqueness constraint is added
- Deleting a unique constraint can only be deleted by deleting a unique index
- You need to specify a unique index name when deleting , The unique index name is the same as the unique constraint name
- If you do not specify a name when creating a unique constraint , If it's a single column , The default is the same as the column name ; If it's a composite column , Then default and () The first column in the list has the same name . You can also customize the uniqueness constraint name
1.2.2.5.2 Code
-- Look at the index
SHOW INDEX FROM test2;
-- Delete unique constraint
ALTER TABLE test2 DROP INDEX salary;
1.2.3 Primary key constraint
1.2.3.1 effect
Used to uniquely identify a row of records in the table .
1.2.3.2 keyword
primary key
1.2.3.3 characteristic
- A table can have at most one primary key constraint , You can create a primary key constraint at the column level , You can also create... At the table level
- The primary key constraint corresponds to one or more columns in the table ( Composite primary key )
- If it is a multi column composite primary key constraint , Then none of these columns are allowed to be null , And the combined value is not allowed to repeat
- MySQL The primary key name of is always PRIMARY, Even if you name the primary key constraint name, it's useless
- When creating a primary key constraint , By default, the system will establish a corresponding primary key index on the column or column combination ( That can be queried according to the primary key , Query according to the primary key , More efficient ). If the primary key constraint is deleted , The index corresponding to the primary key constraint is automatically deleted
- One thing to note is that , Do not modify the value of the primary key field . Because the primary key is the unique identification of the data record , If you modify the value of the primary key , It may destroy the integrity of the data
1.2.3.4 Add primary key constraint
1.2.3.4.1 Add constraints when creating tables
CREATE TABLE test4 (
id INT PRIMARY KEY, -- Column level constraints
last_name VARCHAR ( 15 ),
salary DECIMAL ( 10, 2 ),
email VARCHAR ( 25 )
);
CREATE TABLE test5 (
id INT,
last_name VARCHAR ( 15 ),
salary DECIMAL ( 10, 2 ),
email VARCHAR ( 25 ),
-- Table level constraints
CONSTRAINT PRIMARY KEY ( id )
);
CREATE TABLE test6 (
id INT,
last_name VARCHAR ( 15 ),
salary DECIMAL ( 10, 2 ),
email VARCHAR ( 25 ),
-- Composite primary key , The two columns are regarded as a whole as the primary key
CONSTRAINT PRIMARY KEY ( id,last_name )
);
1.2.3.4.2 Add constraints when modifying tables
ALTER TABLE test7 ADD PRIMARY KEY(id);
1.2.3.5 Delete constraints
ALTER TABLE test7 DROP PRIMARY KEY;
1.2.4 On the column
1.2.4.1 effect
The value of a field increases automatically
1.2.4.2 keyword
auto_increment
1.2.4.3 characteristic
- A table can only have at most one self growing column
- When a unique identifier or sequential value needs to be generated , Self growth can be set
- The column of the self growing column constraint must be a key column ( Primary key column , Unique key column )
- The data type of a column with a self increasing constraint must be an integer type
- If the auto increment column specifies 0 and null, It will automatically increase based on the current maximum ; If the auto increment column manually specifies a specific value , Direct assignment to a specific value .
1.2.4.4 Add auto increment column
1.2.4.4 .1 Add self incrementing columns when creating tables
CREATE TABLE test8 (
id INT PRIMARY KEY AUTO_INCREMENT, -- Column level constraints
last_name VARCHAR ( 15 ),
salary DECIMAL ( 10, 2 ),
email VARCHAR ( 25 )
);
1.2.4.4 .1 Add auto increment column when modifying the table
ALTER TABLE test9 MODIFY id INT AUTO_INCREMENT;
1.2.4.5 Delete auto increment column
ALTER TABLE test9 MODIFY id INT;
1.2.5 Foreign key constraints
1.2.5.1 effect
Limit the referential integrity of a field in a table .
1.2.5.2 keyword
foreign key
1.2.5.3 characteristic
- From the foreign key column of the table , Must quote / Columns that refer to the primary key or unique constraint of the main table , Because of being dependent / The referenced value must be unique
- When creating a foreign key constraint , If you don't name the foreign key constraint , The default name is not a column name , Instead, it automatically generates a foreign key name ( for example student_ibfk_1;), You can also specify a foreign key constraint name
- establish (CREATE) If you specify a foreign key constraint when using the table , Create the main table first , Then create the slave table
- When deleting a table , Delete from the table first ( Or delete the foreign key constraint first ), Delete the main table
- When the records of the master table are referenced from the slave table , Records in the main table will not be allowed to be deleted , If you want to delete data , You need to delete the data that depends on this record from the table first , Then you can delete the data of the main table
- stay “ From the table ” Specify foreign key constraints in , And a table can establish multiple foreign key constraints
- The foreign key column of the slave table and the column name of the main table can be different , But the data type must be the same , The logical meaning is consistent . If the types are different , When creating a child table , There will be errors “ERROR 1005(HYo00):Can’t create table’database.tablename’(errno:150)”. for example : They all represent the department number , All are int type .
- When creating a foreign key constraint , By default, the system will establish the corresponding common index on the column . But the index name is the column name , Is not the constraint name of a foreign key .( It is very efficient to query according to foreign keys )
- After deleting the foreign key constraint , The corresponding index must be manually deleted
1.2.5.4 Add a foreign key constraint
1.2.5.4.1 Add constraints when creating tables
-- Create the main table
CREATE TABLE dept (
dept_id INT PRIMARY KEY,
dept_name VARCHAR ( 15 )
);
-- Create from table
CREATE TABLE emp (
emp_id INT PRIMARY KEY AUTO_INCREMENT,
emp_name VARCHAR ( 15 ),
department_id INT,
-- Foreign key link
CONSTRAINT fk_emp_dept_id FOREIGN KEY(department_id) REFERENCES dept(dept_id)
);
1.2.5.4.2 Add constraints when modifying tables
-- Create the main table
CREATE TABLE dept2 (
dept_id INT PRIMARY KEY,
dept_name VARCHAR ( 15 )
);
-- Create from table
CREATE TABLE emp2 (
emp_id INT PRIMARY KEY AUTO_INCREMENT,
emp_name VARCHAR ( 15 ),
department_id INT
);
-- Add foreign keys
ALTER TABLE emp2 ADD CONSTRAINT fk_emp2_dept_id FOREIGN KEY(department_id) REFERENCES dept2(dept_id);
1.2.5.5 Delete foreign key constraint
-- Create the main table
CREATE TABLE dept2 (
dept_id INT PRIMARY KEY,
dept_name VARCHAR ( 15 )
);
-- Create from table
CREATE TABLE emp2 (
emp_id INT PRIMARY KEY AUTO_INCREMENT,
emp_name VARCHAR ( 15 ),
department_id INT
);
-- Add foreign keys
ALTER TABLE emp2 ADD CONSTRAINT fk_emp2_dept_id FOREIGN KEY(department_id) REFERENCES dept2(dept_id);
-- Delete foreign key
ALTER TABLE emp2 DROP FOREIGN KEY fk_emp2_dept_id;
-- View the general index corresponding to the foreign key constraint
SHOW INDEX FROM emp2;
-- Delete index ( Indexes are created with the creation of foreign keys , The name is the foreign key constraint name )
ALTER TABLE emp2 DROP INDEX fk_emp2_dept_id;
1.2.6 Check constraint (Mysql8.0 Support )
1.2.6.1 effect
Check whether the value of a field is a symbol xx requirement , Generally refers to the range of values .
1.2.6.2 keyword
CHECK
1.2.6.3 Add check constraints
1.2.6.3.1 Add constraints when creating tables
CREATE TABLE test10(
id INT,
last_name VARCHAR(15),
salary DECIMAL(10,2) CHECK(salary > 2000)
);
1.2.7 Default constraint
1.2.7.1 effect
Give a field / Specify a default value for a column , Once the default value is set , When inserting data , If this field has no explicit assignment , The default value is assigned .
1.2.7.2 keyword
DEFAULT
1.2.7.3 Add check constraints
1.2.7.3.1 Add constraints when creating tables
CREATE TABLE test11(
id INT,
last_name VARCHAR(15),
salary DECIMAL(10,2) DEFAULT(3000)
);
1.2.7.3.2 Add constraints when modifying tables
CREATE TABLE test13(
id INT,
last_name VARCHAR(15),
salary DECIMAL(10,2)
);
ALTER TABLE test13 MODIFY salary DECIMAL(10,2) DEFAULT(3000);
2 How to add constraints
- create table Add constraints when
- altert table Add constraints when 、 Delete constraints
3 How to view constraints in a table
DESC Table name
4 Constraint level

example :
边栏推荐
- Finally got byte offer, 25-year-old inexperienced experience in software testing, to share with you
- "C language programming", 4th Edition, edited by he Qinming and Yan Hui, after class exercise answers Chapter 3 branch structure
- 遷移雲計算工作負載的四個基本策略
- Three core problems of concurrent programming
- Just using the way and method of consuming the Internet to land and practice the industrial Internet will not bring long-term development
- matlab 使用 audioread 、 sound 读取和播放 wav 文件
- Number of palindromes in C language (leetcode)
- matlab 使用 resample 完成重采样
- 10 minutes to get started quickly composition API (setup syntax sugar writing method)
- 电子协会 C语言 1级 32、计算2的幂
猜你喜欢

【LeetCode 43】236. The nearest common ancestor of binary tree

Implementation of Weibo system based on SSM
![[IVX junior engineer training course 10 papers to get certificates] 0708 news page production](/img/ad/a1cb672d2913b6befd6d8779c993ec.jpg)
[IVX junior engineer training course 10 papers to get certificates] 0708 news page production

II Basic structure of radio energy transmission system

k线图形态这样记(口诀篇)

We should make clear the branch prediction

2022年6月国产数据库大事记

Learning note 24 - multi sensor post fusion technology

Leetcode, 3 repeatless longest subsequence

Finally got byte offer, 25-year-old inexperienced experience in software testing, to share with you
随机推荐
Private project practice sharing [Yugong series] February 2022 U3D full stack class 009 unity object creation
The technology boss is ready, and the topic of position C is up to you
[IVX junior engineer training course 10 papers] 02 numerical binding and adaptive website production
Implementation of Weibo system based on SSM
Modeling essays series 124 a simple coding method
[IVX junior engineer training course 10 papers to get certificates] 03 events and guessing numbers games
Single chip microcomputer -- hlk-w801 transplant NES simulator (III)
VARIATIONAL IMAGE COMPRESSION WITH A SCALE HYPERPRIOR文献实验复现
The author is more willing to regard industrial Internet as a concept much richer than consumer Internet
Réseau neuronal convolutif (y compris le Code et l'illustration correspondante)
NeRV: Neural Reflectance and Visibility Fields for Relighting and View Synthesis
np. Where and torch Where usage
Develop those things: how to use go singleton mode to ensure the security of high concurrency of streaming media?
Should enterprises choose server free computing?
Matlab uses audiorecorder and recordblocking to record sound, play to play sound, and audiobook to save sound
[IVX junior engineer training course 10 papers] 05 canvas and aircraft war game production
SQLite 3 of embedded database
matlab 实现语音信号重采样和归一化,并播放比对效果
new和malloc的区别
There are spaces in the for loop variable in the shell -- IFS variable