当前位置:网站首页>MySQL constraints
MySQL constraints
2022-07-05 12:12:00 【ziyi813】
MySql constraint
brief introduction , Concept
constraint
Constraints are actually constraints on the data in the table
effect
The purpose of adding constraints in the design of the table is to ensure the integrity and effectiveness of the records in the table , For example, the value of some columns in the user table cannot be empty , The values of some columns cannot be repeated .
classification
- Primary key constraint (primary key) PK
- Self growth constraints (auto_increment)
- Non empty constraint (not null)
- Uniqueness constraint (unique)
- Zero fill constraint (zerofill)
- Foreign key constraints (foreign key) FK
Primary key constraint primary key
Concept
MySql A primary key constraint is a column or a combination of columns , Its value can uniquely identify each row in the table , Convenient in RDBMS Find a line as soon as possible .
A primary key constraint is equivalent to a unique constraint + A combination of nonnull constraints , Primary key constraint columns are not allowed to be duplicate , Null values are not allowed .
Only one primary key is allowed per table .
The key of the primary key constraint is :primary key
When creating a primary key constraint , By default, the system will establish a unique index on the column and column combination .
Operation primary key
- Add single column primary key
- Add multi column joint primary key
- Delete primary key
constraint Named primary key
Single column primary key
There are two ways to create a single column primary key , One is to specify the primary key while defining the field , One is to specify the primary key after defining the field .
The way 1 grammar :
-- stay create table In the sentence , adopt PRIMARY KEY Keyword to specify the primary key
-- Specify the primary key while defining the field , The syntax is as follows :
crate table Table name (
...
< Field name > < data type > primary key
)
The way 1 Implementation example :
crate table demo(
sid int primay key,
name VARCHAR(20)
);
The way 2 grammar :
-- Define the primary key after defining the field
create table Table name (
...
[constraint < Constraint name >] primary key [ Field name ]
);
The way 2 Realization :
create table demo2(
id int,
name varchar(20),
constraint pk1 primary key (id)
);
Combined the primary key
A primary key consists of multiple fields in a table .
Be careful :
- When the primary key is composed of multiple fields , You cannot declare a primary key constraint directly after a field name
- A table can only have one primary key , A federated primary key is also a primary key
grammar :
create table Table name (
...
primary key ( Field 1, Field 2, Field 3)
);
Example :
create table demo3 (
name varchar(20),
depId int,
num int,
constraint nam1 primary key (name,depId)
);
No field can be empty , Two primary keys cannot be duplicate values at the same time .
Modify table structure and add primary key
grammar :
create table Table name ( ... );
-- adopt alter table modify
ALTER TABLE < Table name > add primary key ( Field list );
Example :
-- Add single column primary key
create table demo4(
id int,
name varchar(20),
depId int
);
alter table demo4 add primary key (id);
Add multi column primary key
alter table demo4 add primary key(id,name);
Delete primary key
Format :
alter table < Data table name > drop primary key;
Realization :
-- Delete single column primary key
alter table demo1 drop primary key;
-- Delete multi column primary key
alter table demo1 drop primary key;
Self growth constraints auto_increment
Concept
When the primary key definition grows , The value of this primary key There is no need for users to enter data 了 , The database system automatically assigns values according to the definition . Every record added , The primary key will automatically grow in the same step size .
By adding auto_increment Property to realize the primary key self growth .
grammar :
Field name data type auto_increment
operation
create table user (
id int primary key auto_increment,
name varchar(20)
);
characteristic
- By default ,auto_increment The initial value of the yes 1, Every new record , field value Add 1.
- Only one field can be used in a table auto_increment constraint , The field must have a unique index , To avoid repetition of serial numbers ( It is the primary key or part of the primary key )
- auto_increment The constrained field must have NOT NULL attribute
- auto_increment The field of constraint can only be integer type (TINYINT, SMALLINT, INT, BIGINT) etc. .
- auto_increment The maximum value of a constraint field is constrained by the data type of the field , If it reaches the upper limit auto_increment It will fail. .
Specify the initial value of the auto increment field
If the first record sets the initial value of this field , Then the newly added record will increase from this initial value . If the number inserted in the table is 1 Bar record id value yes 5, Then the subsequent records will start from 5 Begin to increase .
-- The way 1, When creating a table, specify
create table emp1 (
id int primary key auto_increment,
name varchar(20)
) auto_increment=100;
If there is data in the table , Want to increase the primary key from 1 Start , Then you need to delete this field , Then add it again
-- Delete ID Field
alter table student drop sid;
-- add to sid Field
alter table student add id int(8) not null primary key AUTO_INCREMENT first;
delete and truncate Change of auto increment column after deletion
- delete After that, from the self increase to the last ID Start
- truncate from 1 Start
Non empty constraint
not null
This field cannot be null , It must be worth .
Add non empty constraints :
The way 1:
< Field name > < data type > not null;
The way 2:
alter table Table name modify Field type not null
alter table student modify name varchar(20) not null;
Delete non empty constraints
-- Use it directly modify Keyword modification , No addition not null
alter table student modify name varchar(20);
Unique constraint unique
The record in the field column cannot have duplicate values .
grammar :
-- The way 1
< Field name > < data type > unique
-- The way 2
alter table Table name add constraint Constraint name unique( Column );
Example :
-- Specify... When creating a table
create table student (
id int,
name varchar(20),
phone number varchar(20) unique -- Specify a unique constraint
);
-- Modify table structure
ALTER TABLE student add constraint Constraint name unique( Column )
-- Delete unique constraint
ALTER TABLE student drop index < Unique constraint name >;
Default constraint
MySQL The default value constraint is used to specify the default value of a column .
grammar
-- The way 1:
< Field name > < data type > default < The default value is >
-- The way 2:
alter table Table name modify list type default The default value is ;
Example
-- The way 1
create table student (
id int,
name varchar(20),
address varchar(20) default ' Beijing ' -- Specify the default constraint
);
-- The way 2
alter table student modify age int(20) default 20;
Zero fill constraint
Concept
- When inserting data , When the value of this field When the length of is less than the defined length , This value will be Put the corresponding... In front of 0
- zerofill The default is int(10)
- When using zerofill when , By default, it will automatically add unsigned( Unsigned ) attribute , Use unsigned After attribute , The value range is the original value Of 2 times , for example : The sign is -128~+127, No sign is 0-256
-- Use in a similar way , The attribute is zerofill
create table demo1 (
id int zerofill, -- Zero fill constraint
name varchar(20)
);
-- Delete
alter table demo1 modify id int; -- Directly reset the properties of the field column , Remove zerofill Key words can be used
summary
- Classification of constraints
- The role of constraints
- Use of constraints
边栏推荐
- 2022年国内云管平台厂商哪家好?为什么?
- 【云原生 | Kubernetes篇】Ingress案例实战(十三)
- Pytorch linear regression
- [untitled]
- 自动化测试生命周期
- JS for循环 循环次数异常
- 想问问,如何选择券商?在线开户是很安全么?
- byte2String、string2Byte
- Want to ask, how to choose a securities firm? Is it safe to open an account online?
- 16 channel water lamp experiment based on Proteus (assembly language)
猜你喜欢
The most comprehensive new database in the whole network, multidimensional table platform inventory note, flowus, airtable, seatable, Vig table Vika, flying Book Multidimensional table, heipayun, Zhix
Redirection of redis cluster
MySQL splits strings for conditional queries
The survey shows that traditional data security tools cannot resist blackmail software attacks in 60% of cases
【pytorch 修改预训练模型:实测加载预训练模型与模型随机初始化差别不大】
Principle of redis cluster mode
yolov5目標檢測神經網絡——損失函數計算原理
Liunx prohibit Ping explain the different usage of traceroute
全网最全的新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
Mongodb replica set
随机推荐
byte2String、string2Byte
ABAP table lookup program
Image hyperspectral experiment: srcnn/fsrcnn
Simply solve the problem that the node in the redis cluster cannot read data (error) moved
【ijkplayer】when i compile file “compile-ffmpeg.sh“ ,it show error “No such file or directory“.
Matlab boundarymask function (find the boundary of the divided area)
Pytorch linear regression
POJ-2499 Binary Tree
Xi IO flow
vscode快捷键
[loss functions of L1, L2 and smooth L1]
Pytorch MLP
[calculation of loss in yolov3]
liunx禁ping 详解traceroute的不同用法
[yolov5.yaml parsing]
Hiengine: comparable to the local cloud native memory database engine
Design of music box based on assembly language
网络五连鞭
Swift - enables textview to be highly adaptive
16 channel water lamp experiment based on Proteus (assembly language)