当前位置:网站首页>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 :
边栏推荐
- Memorabilia of domestic database in June 2022
- 自动浏览拼多多商品
- Game thinking 15: thinking about the whole region and sub region Services
- Ks006 student achievement management system based on SSM
- 【视频】马尔可夫链原理可视化解释与R语言区制转换MRS实例|数据分享
- 企业应该选择无服务器计算吗?
- 基于SSM实现微博系统
- np.where 和 torch.where 用法
- [IVX junior engineer training course 10 papers] 04 canvas and a group photo of IVX and me
- Learning notes 25 - multi sensor front fusion technology
猜你喜欢
Learning note 3 -- Key Technologies of high-precision map (Part 1)
Introduction to ffmpeg Lib
How can I batch produce the same title for the video?
[Floyd] post disaster reconstruction
6-3漏洞利用-SSH环境搭建
Game thinking 15: thinking about the whole region and sub region Services
[disease detection] realize lung cancer detection system based on BP neural network, including GUI interface
Implementation of Weibo system based on SSM
This is the report that leaders like! Learn dynamic visual charts, promotion and salary increase are indispensable
技术大佬准备就绪,话题C位由你决定
随机推荐
【视频】马尔可夫链原理可视化解释与R语言区制转换MRS实例|数据分享
[IVX junior engineer training course 10 papers] 02 numerical binding and adaptive website production
Single chip microcomputer -- hlk-w801 transplant NES simulator (III)
The difference between new and malloc
Parted command
Basic concepts of machine learning
Leetcode, 3 repeatless longest subsequence
k线图形态这样记(口诀篇)
卷积神经网络(包含代码与相应图解)
基于SSM实现微博系统
II Basic structure of radio energy transmission system
[Obsidian] wechat is sent to Obsidian using remotely save S3 compatibility
Another programmer "deleted the library and ran away", deleted the code of the retail platform, and was sentenced to 10 months
SQLite 3 of embedded database
How can the tsingsee Qingxi platform play multiple videos at the same time on the same node?
[IVX junior engineer training course 10 papers] 06 database and services
matlab 实现语音信号重采样和归一化,并播放比对效果
What are the skills of spot gold analysis?
Volume compression, decompression
Ubuntu20.04 PostgreSQL 14 installation configuration record