当前位置:网站首页>I. creation and constraint of MySQL table
I. creation and constraint of MySQL table
2022-07-26 13:34:00 【Slightly cool autumn】
Author's brief introduction :C/C++ New star creators in the field , by C++ and java In the struggle
Personal community : Cool autumn community
Series column :MySQL A little
Recommend a simulated interview 、 Brush Title artifact Register for free questions
Preface
The last blog shared
MySQLDownload and configuration of environment variables , And simply create the database and tables . This blog will share the syntax of database creation and destruction and explain it in detail MySQL The creation code of tables and the use of constraints , Strive for one article to grasp these knowledge points !
List of articles
One 、 Establishment and destruction of database
Building a database :
create database [if not exists] Database name [default charset Character set ]
tips: brackets [] The contents can be omitted
- add
if not existsThe meaning is : If this database does not exist, it will be created default charset Character setIs to set the character set when creating the database
Destroy database :
drop database [if exists] Database name
tips: The meanings of the parts that can be omitted are the same as above
Two 、 Creation and destruction of tables
1、 The establishment of tables
grammar :
create table [if not exists] Table name (
Field name data type [ constraint ],
Field name data type [ constraint ],
...( The last field cannot have a comma )
)
1.1、 Naming rules
- Table names are usually in the form of
t_start - Key fields are usually represented by
Table name abbreviation _start - MySQL Case insensitive , Cannot use keyword naming , Multiple parts are underlined
1.2、 data type
Data types to master :
- Integers :int、integer、bigint
- decimal :decimal
- character string :varchar
- enumeration :enum
- date :datatime
Use advice :
- When the field number must be greater than 0 And unsigned numbers can be used without subtraction
unsigned, It is usually not recommended to floatanddoubleThere is Precision problem , follow-up mysql Will no longer support- char and
vercharThe underlying implementation is consistent when saving multiple characters , It's just that the mode of occupying space is different , Not recommended char, Because it may waste space timestampThe upper limit is too low ,date and time Unpractical , Therefore, it is suggested to usedatetime
2、 Table constraint concept
2.1、 Constraint Preview
| constraint | explain | explain |
|---|---|---|
| primary key | Primary key | Used to mark a column as the primary key column |
| not null | Non empty | Constraint the column value cannot be empty |
| unique | only | Constrain that the column value cannot be repeated |
| default | Default | Set the default value for this column |
| foreign key | Foreign keys | The flag column is the foreign key value |
| check | Check constraint | MySQL I won't support it |
2.2、 Characteristics and functions
- Primary key
- effect : It can be used as a unique identifier to specifically lock a row of data
- characteristic : Non empty and unique
- A table can have at most one primary key column
- Non empty
- characteristic : The value can not be null, Must set
- only
- characteristic : The value can be null, And there can be multiple null, This constraint is only valid for values that already exist
Non empty constraint + Unique constraint Not equal to Primary key constraint
- characteristic : The value can be null, And there can be multiple null, This constraint is only valid for values that already exist
- Default
- characteristic : If the column is not explicitly assigned , Then use the default value to store
- grammar :
default( value )
The use of foreign keys is explained in detail below
3、 Table constraints are specifically used
3.1、 Column level constraints
Define the constraint directly in the declaration of the column
Examples of use :
-- id、 full name 、 Age 、 Gender 、 height 、 Birthday
create table if not exists t_person(
p_id int primary key,-- Primary key
p_name varchar(50) unique not null,-- only + Non empty
age tinyint unsigned not null,-- Non empty An unsigned number 0-255
sex enum(' male ',' Woman ',' Ultraman ') default ' Ultraman ',-- Default
height decimal(4,1), -- All in all 4 position , The decimal point takes up 1 position :000.0
birthday datetime
)
3.2、 Table level constraints
Define constraints separately below all columns ,not null and default No table level constraints
grammar :[constraint Custom constraint name ] Constraint type ( Field name )
Examples of use :
create table if not exists t_person(
p_id int,-- Primary key
p_name varchar(50) not null,-- only + Non empty
age tinyint unsigned not null,-- Non empty An unsigned number 0-255
sex enum(' male ',' Woman ',' Ultraman ') default ' Ultraman ',-- Default
height decimal(4,1), -- All in all 4 position , The decimal point takes up 1 position :000.0
birthday datetime,
-- Table level constraints
primary key(p_id),-- to p_id Add primary key constraint
constraint un_name unique(p_name)-- to p_name Add unique constraints
)
3.3、 Foreign key constraints
- effect : Used to indicate the relationship between two tables , Must be used in conjunction with another table
- characteristic :
- The connection must be from another table Primary key or unique column
- The value of the foreign key column You can't customize , Must be from a value that already exists in the column associated with another table
- The value can be null, Is not the only
- Must use Table level constraints establish
- grammar :
foreign key( Field name )referencesOther table names ( Connection field names of other tables ) - Use :
- Table creation sequence : First create a table without foreign keys , Create a table with foreign keys
- Deletion order : Delete the foreign key first , Delete any foreign keys
- Foreign key column data type Must be consistent with the connected column
Examples of use :
-- Class table :id, Class name
create table t_class(
c_id int PRIMARY KEY,
c_name varchar(20) not null
)
-- Student list :id, full name , Class id
create table t_student(
s_id int PRIMARY KEY,
s_name varchar(20) not null,
c_id int not null ,
-- Table level constraints
FOREIGN KEY(c_id) REFERENCES t_class(c_id)
)
4、 Destruction of tables
grammar :drop table [if exists] Table name
matters needing attention :
stay 3.3 Foreign key constraints are specifically used for tables with foreign keys , Delete the table with foreign keys first , Delete the table without foreign keys drop table t_student – Delete the student list first drop table t_class – To delete the class table
Conclusion
I hope this blog can help you , Let's make progress together !!!
边栏推荐
- Official announcement! Edweisen group and Baidu xirang reached a deep co creation cooperation
- 历时15年、拥有5亿用户的飞信,彻底死了
- 从标注好的xml文件中截取坐标点(人脸框四个点坐标)人脸图像并保存在指定文件夹
- Leetcode 263. ugly number
- Activity.onStop() 延迟10秒?精彩绝伦的排查历程
- MySQL data directory (1) -- database structure (24)
- Codeforces round 810 (Div. 2) [competition record]
- JSON数据传递参数&日期型参数传递
- Win11+VS2019配置YOLOX
- Photoshop (cc2020) unfinished
猜你喜欢

ROS2学习(1)ROS2简述

Official announcement! Edweisen group and Baidu xirang reached a deep co creation cooperation

How to write the introduction of GIS method journals and papers?

【花雕动手做】有趣好玩的音乐可视化系列小项目(12)---米管快速节奏灯

One stroke problem (Chinese postman problem)

算法--连续数列(Kotlin)

Target detection network r-cnn series

【Oauth2】五、OAuth2LoginAuthenticationFilter

云智技术论坛工业专场 明天见!

flutter多渠道打包运行
随机推荐
Brief introduction of reflection mechanism
JUC总结
Dimension disaster dimension disaster suspense
【花雕动手做】有趣好玩的音乐可视化系列小项目(13)---有机棒立柱灯
Unity中序列化类为json格式
LCL三相pwm整流器(逆变器)
重押海外:阿里、京东、顺丰再拼“内力”
Tupu 3D visual national style design | collision between technology and culture "cool" spark“
Exploration on cache design optimization of community like business
带你熟悉云网络的“电话簿”:DNS
How to write the introduction of GIS method journals and papers?
Codeforces Round #810 (Div. 2)【比赛记录】
B+ tree (4) joint index -- MySQL from entry to proficiency (16)
2022年,我们只用一个月就“送走”了这么多互联网产品
Jenkins 中 shell 脚本执行失败却不自行退出
估值15亿美元的独角兽被爆裁员,又一赛道遇冷?
[oauth2] VIII. Configuration logic of oauth2 login -oauth2loginconfigurer and oauth2clientconfigurer
Sword finger offer (x): rectangular coverage
Precautions for triggering pytest.main() from other files
Concept and handling of exceptions