当前位置:网站首页>I. creation and constraint of MySQL table
I. creation and constraint of MySQL table
2022-07-29 03:48:00 【m0_ sixty-seven million three hundred and ninety-one thousand t】
Author's brief introduction :C/C++ New star creators in the field , by C++ and java In the struggle
Personal community : 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
- Two 、 Creation and destruction of tables
- Conclusion
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 !!!
边栏推荐
- Typescript from entry to mastery (XXI) generic types in classes
- Configmap configuration and secret encryption
- Practical application cases of digital Twins - smart energy
- Getting started with caspin
- 1. Header file - Comment - namespace - standard input / output stream
- Deep understanding of Base64 underlying principles
- Exness: dove resolution helped gold rebound, and the focus turned to U.S. GDP
- 关于ALV格式控制部分的写法
- Code ~ hide or disable the status bar and virtual keys
- EMD 经验模态分解
猜你喜欢

Vs code must know and know 20 shortcut keys!

Process tracking of ribbon principle

EMD 经验模态分解

1. Mx6u driver development-2-led driver

CUB_ Visualization of key points in 200 bird dataset

Shopify seller: EDM marketing should be combined with salesmartly to easily get the conversion rate

What have I learned from 200 machine learning tools?

最新二开版漫画小说听书三合一完整源码/整合免签接口/搭建教程/带采集接口

UCOS任务切换过程

内连接和左连接简单案例
随机推荐
1985-2020(8个版次)全球地表覆盖下载与介绍
Introduction to static routing and dynamic routing protocols OSPF and rip and static routing configuration commands
内连接和左连接简单案例
(newcoder 15079) irrelevant (inclusion exclusion principle)
Solve the problem of garbled code when opening the project code in idea
【redis系列】字符串数据结构
Typescript from introduction to proficiency (XXIV) using import syntax
Simple cases of inner connection and left connection
向日葵远程控制为何采用BGP服务器?自动最优路线、跨运营商高速传输
Deep understanding of Base64 underlying principles
Casbin入门
Connect with third-party QQ login
LDP --- 标签分发协议
What you see and think in Microsoft
Getting started with caspin
Excel拼接数据库语句
企业网的三层架构
数据挖掘——关联分析例题代码实现(下)
Batch production and upload sales NFT opensea eth polygon
Typescript from getting started to mastering (XX) function generics