当前位置:网站首页>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 !!!
边栏推荐
- JSON data transfer parameters & date type parameter transfer
- Leetcode 2119. number reversed twice
- Pytorch学习笔记(三)模型的使用、修改、训练(CPU/GPU)及验证
- With 8 years of product experience, I have summarized these practical experience of continuous and efficient research and development
- B+ tree index use (8) sorting use and precautions (20)
- 飞盘,2022年“黑红”顶流
- 7-25 0-1 backpack (50 points)
- [flower carving hands-on] interesting and fun music visualization series small project (13) -- organic rod column lamp
- AI theory knowledge map 1 Foundation
- Oom caused by improper use of multithreading
猜你喜欢
Exploration on cache design optimization of community like business
![[flower carving hands-on] fun music visualization series small project (12) -- meter tube fast rhythm light](/img/99/6581b8a576e59a13aa4e977e3a1b70.jpg)
[flower carving hands-on] fun music visualization series small project (12) -- meter tube fast rhythm light

Learn about Pinia state getters actions plugins

《Kotlin系列》之MVVM架构封装(kotlin+mvvm)

Photoshop(CC2020)未完

官宣!艾德韦宣集团与百度希壤达成深度共创合作

Oom caused by improper use of multithreading

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

Chat system based on webrtc and websocket

【花雕动手做】有趣好玩的音乐可视化系列小项目(13)---有机棒立柱灯
随机推荐
[flower carving hands-on] fun music visualization series small project (12) -- meter tube fast rhythm light
【黑马早报】字节旗下多款APP下架;三只松鼠脱氧剂泄露致孕妇误食;CBA公司向B站索赔4.06亿;马斯克否认与谷歌创始人妻子有婚外情...
详解关系抽取模型 CasRel
AI theory knowledge map 1 Foundation
The last time I heard about eBay, or the last time
Win11+VS2019配置YOLOX
Win11+vs2019 configuration yolox
Time complexity and space complexity
【开源之美】nanomsg(2) :req/rep 模式
Basic sentence structure of English ----- origin
Student examination system based on C #
JUC总结
Detailed explanation of factory mode
估值15亿美元的独角兽被爆裁员,又一赛道遇冷?
AI-理论-知识图谱1-基础
LCL三相pwm整流器(逆变器)
LeetCode 69. x 的平方根
Outline design specification
Leetcode 263. ugly number
Codeforces round 810 (Div. 2) [competition record]