当前位置:网站首页>Database day-3
Database day-3
2022-06-09 13:04:00 【Right ear needs oil】
Catalog
Complete syntax for creating tables
auto_increment Self increasing
The relationship between tables
Complete syntax for creating tables
auto_increment Self increasing
The relationship between tables
Daily test
What do you know MySQL Storage engine , Talk about their characteristics briefly
Innodb 5.5 The default storage engine used after version , Storing data is more secure
blackhole The black hole will disappear when it is stored
memory Memory storage , The data disappears after exiting
MyIsam 5.5 The default storage engine before version , The stored data is called Innodb faster
Complete syntax and considerations for creating tables
create table indicate ( Field name Field type () constraint condition );
MySQL What are the basic data types
Integer type
floating-point
Character
enumeration , aggregate
Yesterday's review
Storage engine
""" There should be different processing mechanisms for different data see MySQL All storage engines show engines; Innodb MySQL5.5 The default storage engine after version Support transactions Row lock Foreign keys Data is more secure Creating a table generates two files Table structure file Table data file MyIsam MySQL5.5 The default storage engine before version Although it has no data security Innodb reliable But the query speed is faster Innodb faster Creating a table generates three files Table structure file Table data file Table index file memory Memory engine Temporary data storage Creating a table will generate a file Table structure file blackhole Black holes Creating a table will generate a file Table structure file """
Complete syntax for creating tables
# grammar
create table Table name (
Field name 1 Field type ( Width ) constraint condition ,
Field name 2 Field type ( Width ) constraint condition ,
Field name 3 Field type ( Width ) constraint condition
)
# Be careful
1 Field names cannot be repeated in the same table
2 Width and constraints are optional Field name and field type are required
3 The last field cannot be followed by a comma
# In general, the width is the limit on the storage data
# Constraints can have multiple Is an additional limitation
Strict mode
# When using a database Try to make the database work less !!!
show variables like '%mode';
set session
set global sql_mode = 'STRICT_TRANS_TABLES';Basic data type
"""
integer
TINYINT INT BIGINT
The default is signed
int(4)
The numbers in integer brackets are not used to restrict storage
If there are less than four digits, fill them with spaces by default
Enough for four, how many to save
zerofill
summary When defining integer fields in the future In fact, you don't need to add your own width
Because integers have their own width It's enough to show all the numbers
floating-point
float(255,30)
double(255,30)
decimal(65,30)
As long as it's floating point There are two numbers after the brackets
The first number represents the total number of digits
The second digit represents the decimal place
accuracy
float < double < decimal
Expand : In fact, in actual production A lot of data that seems to need to be stored in integer or floating-point type
Internal may be stored in character type
Character type
char(4) Fixed length
Only a maximum of four characters can be stored Beyond error reporting Do not exceed the default to complete with blank space
varchar(4) Lengthening
Only a maximum of four characters can be stored Beyond error reporting Not more than a few save a few
char Vs varchar
char
Waste space
Access convenient Simple violence Directly access according to the fixed number of bits
varchar
Save a space
But compared to char Its access speed is slow
Because it needs a when accessing data Headlines
Previously used char quite a lot Limit varchar quite a lot
Time type
date Specific date
datetime Mm / DD / yyyy HHM / S
time Minutes and seconds
year year ( Limited scope )
Enumeration and collection type
enumeration enum
A commonplace
aggregate set
More than a multiple-choice ( You can also single select )
gender enum('male','female','others')
hobby set('read','sangna','DBJ','hecha')
Your data can only be sourced from the options provided by the field You can't make it up
"""constraint condition
"""
zerofill
unsigned
not null
"""Summary of today's content
constraint condition
Create relationships between tables ( constraint )( a key )
Modify the complete syntax of the table
Copy table
Assignment ( How to judge table relationships and how to establish table relationships )
Today's content is detailed
constraint condition
default The default value is
# Supplementary information When inserting data, you can specify fields
create table t1(
id int,
name char(16)
);
insert into t1(name,id) values('jason',1);
create table t2(
id int,
name char(16),
gender enum('male','female','others') default 'male'
);
insert into t2(id,name) values(1,'jason');
insert into t2 values(2,'egon','female');unique only
# It's unique
create table t3(
id int unique,
name char(16)
);
insert into t3 values(1,'jason'),(1,'egon');# Report errors
insert into t3 values(1,'jason'),(2,'egon');
# Joint only
"""
ip and port Represents the unique address of the host
A single can be repeated , But loading together must be unique
"""
create table t4(
id int,
ip char(16),
port int,
unique(ip,port)
);
insert into t4 values(1,'127.0.0.1',8080);
insert into t4 values(2,'127.0.0.1',8081);
insert into t4 values(3,'127.0.0.2',8080);
insert into t4 values(4,'127.0.0.1',8080); Report errors primary key Primary key
"""
1. In terms of constraint effects alone primary key Equivalent to not null + unique
Non empty and unique !!!
"""
create table t5(id int primary key);
insert into t5 values(null); Report errors
insert into t5 values(1),(1); Report errors
insert into t5 values(1),(2);
"""
2. In addition to its binding effect It's still Innodb Storage engine organizes data based on
Innodb When creating tables, the storage engine must have primary key
Because it's like a catalog of books It can help prompt query efficiency and is also the basis for creating tables
"""
# 1 There is only one primary key in a table If you don't set the primary key You will search from top to bottom until you encounter a non empty and unique field, which will be automatically upgraded to a primary key
create table t6(
id int,
name char(16),
age int not null unique,
addr char(32) not null unique
);
# 2 If there is no primary key or any other non empty and unique field in the table that Innodb A hidden field provided internally will be used as the primary key , Hiding means you can't use it The query speed cannot be prompted
# 3 A table should usually have a primary key field And usually will id/uid/sid Field as primary key
# Single field primary key
create table t5(
id int primary key
name char(16)
);
# Combined the primary key ( Multiple fields are combined as the primary key of the table In essence, it is also a primary key )
create table t7(
ip char(16),
port int,
primary key(ip,port)
);
"""
Also means that In the future, when we create tables id The field must be added primary key
"""auto_increment Self increasing
# When there are too many numbers It is too troublesome to maintain artificially
create table t8(
id int primary key auto_increment,
name char(16)
);
insert into t8(name) values('jason'),('egon'),('kevin');
# Be careful auto_increment It is usually added to the primary key You cannot add... To a normal field
create table t9(
id int primary key auto_increment,
name char(16),
cid int auto_increment
);
ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a keyConclusion
"""
In the future, you can create a table id( Unique identification of the data id、uid、sid) Field time
id int primary key auto_increment
"""
Add
delete from t1 After deleting the data in the table The self increment of the primary key will not stop
truncate t1 Clear the table data and reset the primary key
The relationship between tables
"""
Define an employee table There are many fields in the table
id name gender dep_name dep_desc
"""
# 1 The organizational structure of the table is not very clear ( Can be ignored )
# 2 Waste hard disk space ( Can be ignored )
# 3 The scalability of the data is very poor ( Something that cannot be ignored )
# How to optimize ?
""" The above problem is similar to that you write all the code in one py In file """
Split employee table Employee table and department table Foreign keys
"""
Foreign keys are used to help us establish the relationship between tables
foreign key
"""
Table relations
"""
There are at most four relationships between tables
One-to-many relation
stay MySQL There is no more one-to-one talk in the relationship
One to many For one more It's called one to many !!!
Many to many relationship
One to one relationship
It doesn't matter.
"""
One-to-many relation
"""When judging the relationship between tables Not familiar with the situation in the early stage Be sure to follow my advice to youThe perspective-taking Consider from the perspective of two tablesTake employee table and department table for exampleStand on the employee list firstThink about whether an employee can correspond to multiple departments ( Can one employee data correspond to multiple Department data )You can't !!!( It is impossible to draw a direct conclusion Be sure to consider both tables completely )Then stand on the Department tableThink about whether a department can correspond to multiple employees ( Can a department data correspond to multiple employee data )can !!!Come to the conclusionThe employee table and department represent one-way one to manySo the table relationship is one to many"""foreign key1 One to many table relationship Foreign key fields are built in More sides2 When creating tables It must be built first Associated table3 When entering data You must also enter Associated table# SQL Statement to establish a table relationshipcreate table dep(id int primary key auto_increment,dep_name char(16),dep_desc char(32));create table emp(id int primary key auto_increment,name char(16),gender enum('male','female','others') default 'male',dep_id int,foreign key(dep_id) references dep(id));insert into dep(dep_name,dep_desc) values('sb Teaching department ',' Teaching and educating '),(' The Ministry of Foreign Affairs ',' Multiparty diplomacy '),('nb Technology Department ',' Department with limited technical capacity ');insert into emp(name,dep_id) values('jason',2),('egon',1),('tank',1),('kevin',3);# modify dep Inside the watch id Fieldupdate dep set id=200 where id=2; no way# Delete dep The data in the tabledelete from dep; no way# 1 Delete the employee data corresponding to the teaching department first Then delete the DepartmentThe operation is too cumbersome# 2 Truly realize the relationship between dataUpdates are synchronizedDelete synchronously"""update cascade >>> Synchronize updatescascading deletion >>> Sync delete"""create table dep(id int primary key auto_increment,dep_name char(16),dep_desc char(32));create table emp(id int primary key auto_increment,name char(16),gender enum('male','female','others') default 'male',dep_id int,foreign key(dep_id) references dep(id)on update cascade # Synchronize updateson delete cascade # Sync delete);insert into dep(dep_name,dep_desc) values('sb Teaching department ',' Teaching and educating '),(' The Ministry of Foreign Affairs ',' Multiparty diplomacy '),('nb Technology Department ',' Department with limited technical capacity ');insert into emp(name,dep_id) values('jason',2),('egon',1),('tank',1),('kevin',3);
Many to many
"""
Book list and author list
"""
create table book(
id int primary key auto_increment,
title varchar(32),
price int,
author_id int,
foreign key(author_id) references author(id)
on update cascade # Synchronize updates
on delete cascade # Sync delete
);
create table author(
id int primary key auto_increment,
name varchar(32),
age int,
book_id int,
foreign key(book_id) references book(id)
on update cascade # Synchronize updates
on delete cascade # Sync delete
);
"""
Create... As described above Don't try to succeed at all !!!
In fact, we just want to record the relationship between books and authors
For many to many field table relationships You cannot create foreign keys in two existing tables
I need you to open another one alone It is specially used to store the relationship between the data of two tables
"""
create table book(
id int primary key auto_increment,
title varchar(32),
price int
);
create table author(
id int primary key auto_increment,
name varchar(32),
age int
);
create table book2author(
id int primary key auto_increment,
author_id int,
book_id int,
foreign key(author_id) references author(id)
on update cascade # Synchronize updates
on delete cascade, # Sync delete
foreign key(book_id) references book(id)
on update cascade # Synchronize updates
on delete cascade # Sync delete
);One to many
"""
id name age addr phone hobby email........
If a table has too many fields Not all fields can be used in every query
Split the watch in two
User table
User table
id name age
User details table
id addr phone hobby email........
Standing user table
Can a user correspond to multiple user details You can't !!!
Stand on the detail sheet
Can a detail belong to multiple users You can't !!!
Conclusion : One way one to many doesn't hold So the table relationship between the two at this time
It's one-on-one
Or it doesn't matter ( Good judgment )
Customer form and student form
Before you sign up, you are a client
After signing up, the students ( During this period, some customers will not sign up )
"""
one-on-one Foreign key fields can be created on either side But it is recommended that you build it in a table with high query frequency
create table authordetail(
id int primary key auto_increment,
phone int,
addr varchar(64)
);
create table author(
id int primary key auto_increment,
name varchar(32),
age int,
authordetail_id int unique,
foreign key(authordetail_id) references authordetail(id)
on update cascade # Synchronize updates
on delete cascade # Sync delete Modify table
# MySQL Case insensitive
"""
1 Modify the name of the table
alter table Table name rename The new name of the table ;
2 Add fields
alter table Table name add Field name Field type ( Width ) constraint condition ;
alter table Table name add Field name Field type ( Width ) constraint condition first;
alter table Table name add Field name Field type ( Width ) constraint condition after Field name ;
3 Delete field
alter table Table name drop Field name ;
4 Modify fields
alter table Table name modify Field name Field type ( Width ) constraint condition ;
alter table Table name change Old field name new field name Field type ( Width ) constraint condition ;
"""Copy table
"""
We sql The result of a statement query is actually a virtual table
"""
create table Table name select * from Old table ; Cannot copy primary key Foreign keys ...
create table new_dep2 select * from dep where id>3;
Assignment
practice :
Account information table , User group , Host table , Host group
# User table
create table user(
id int not null unique auto_increment,
username varchar(20) not null,
password varchar(50) not null,
primary key(username,password)
);
# User group table
create table usergroup(
id int primary key auto_increment,
groupname varchar(20) not null unique
);
# Host table
create table host(
id int primary key auto_increment,
ip char(15) not null unique default '127.0.0.1'
);
# Line of business table
create table business(
id int primary key auto_increment,
business varchar(20) not null unique
);
# Build relationship :user And usergroup
create table user2usergroup(
id int not null unique auto_increment,
user_id int not null,
group_id int not null,
primary key(user_id,group_id),
foreign key(user_id) references user(id),
foreign key(group_id) references usergroup(id)
);
# Build relationship :host And business
create table host2business(
id int not null unique auto_increment,
host_id int not null,
business_id int not null,
primary key(host_id,business_id),
foreign key(host_id) references host(id),
foreign key(business_id) references business(id)
);
# Build relationship :user And host
create table user2host(
id int not null unique auto_increment,
user_id int not null,
host_id int not null,
primary key(user_id,host_id),
foreign key(user_id) references user(id),
foreign key(host_id) references host(id)
);practice
# Class table
cid caption
# Student list
sid sname gender class_id
# The teacher table
tid tname
# The curriculum
cid cname teacher_id
# League tables
sid student_id course_id number边栏推荐
猜你喜欢
随机推荐
数据库day-6
AVR与ARM区别以及常用Arduino
js中const,var,let定义变量的区别
Connaissance de base de l'analyse modale que l'Ingénieur devrait connaître
【C语言练习——打印正方形及其变形】
[redis advanced]
【SignalR全套系列】之在.Net Core 中实现SignalR实时通信
使用 KubeKey 搭建 Kubernetes/KubeSphere 环境的'心路(累)历程'
Qpprocess class Usage Summary
[NOIP2015 提高组] 运输计划
[memcached and redis]
微信小程序页面之间三种传值方式详解
[code learning] batch extraction of the first page of the paper (PDF)
json、jq实现三级联动选择框方法一
【Redis高级】
[Prometheus summary.observe method]
【C语言练习——打印整数二进制的奇数位和偶数位】
Make qcombobox drop down a tree list with check boxes
[unity TMP external font import problem] TMP Chinese, generate fonts into TMP_ Fontasset FAQs
NVIDIA releases the latest version of Tao toolkit to further simplify and accelerate AI model creation








