当前位置:网站首页>MySQL learns the relationship between Day2 Sorting Query / aggregation function / grouping query / paging query / constraint / multiple tables
MySQL learns the relationship between Day2 Sorting Query / aggregation function / grouping query / paging query / constraint / multiple tables
2022-07-27 18:34:00 【Z know and do t】
One 、DQL Query statement
1.1 Sort query

SELECT * FROM student ORDER BY math; -- The default is ascending ASC
SELECT * FROM student ORDER BY math DESC; -- Descending
-- Rank according to math scores , If the math scores are the same They are ranked according to their English scores
SELECT * FROM student ORDER BY math ASC,english ASC;
1.2 Aggregate functions

SELECT COUNT(NAME) FROM student;
SELECT COUNT(IFNULL (english,0)) The number of FROM student;
SELECT MIN(math) FROM student;
SELECT MAX(english) FROM student;
SELECT SUM(english) FROM student;
SELECT AVG(math) FROM student;
1.3 Group query

-- Group by sex , Check the men separately 、 The average score of female students
SELECT sex,AVG(math)FROM student GROUP BY sex;
-- Group by sex , Check the men separately 、 Number of female students
SELECT sex,AVG(math),COUNT(id)FROM student GROUP BY sex;
-- Group by sex , Check the men separately 、 The average score of female students , The score is below 70 Points do not participate in grouping
SELECT sex,AVG(math),COUNT(id) FROM student WHERE math > 70 GROUP BY sex;
-- Group by sex , Check the men separately 、 The average score of female students , The score is below 70 Points do not participate in grouping , After grouping, the number of people should be greater than 2 personal
SELECT sex,AVG(math),COUNT(id) FROM student WHERE math > 70 GROUP BY sex HAVING COUNT(id)>2;
SELECT sex,AVG(math),COUNT(id) The number of FROM student WHERE math > 70 GROUP BY sex HAVING The number of >2;
1.4 Paging query

-- Three records per page
SELECT *FROM student LIMIT 0,3; -- first page
SELECT * FROM student LIMIT 3,3; -- The second page
SELECT * FROM student LIMIT 6,3; -- The third page
-- The formula : Index started = ( The current page number -1) * Number of entries per page
Two 、 constraint
2.1 summary
constraint : Limit the data in the table , Make sure the data is correct 、 Effectiveness and integrity 
2.2 Non empty constraint

-- Create a table and add a non empty constraint
CREATE TABLE stu(
id INT,
NAME VARCHAR(20) NOT NULL
);
-- Delete name Non empty constraint of
ALTER TABLE stu MODIFY NAME VARCHAR(20);
-- Add a non empty constraint after creating the table
ALTER TABLE stu MODIFY NAME VARCHAR(20) NOT NULL;
SELECT * FROM stu;
2.2 Unique constraint

-- Create a table Add unique constraints
CREATE TABLE stu2(
id INT,
phone_number VARCHAR(20) UNIQUE -- Added a unique constraint
);
-- Be careful mysql in , There can be multiple column values limited by unique constraints null
-- Delete unique constraint
ALTER TABLE stu2 DROP INDEX phone_number ;
-- Add a unique constraint after creating the table
ALTER TABLE stu2 MODIFY phone_number VARCHAR(20) UNIQUE;
SELECT * FROM stu2;
2.3 Primary key constraint

CREATE TABLE stu1(
id INT PRIMARY KEY, -- to id Add primary key constraint
NAME VARCHAR(20)
);
SELECT *FROM stu1;
-- Delete gradually
ALTER TABLE stu1 DROP PRIMARY KEY;
-- Add the primary key after creating the table
ALTER TABLE stu1 MODIFY id INT PRIMARY KEY;
2.3 Primary key constraint — Automatic growth

CREATE TABLE stu2(
id INT PRIMARY KEY AUTO_INCREMENT, -- to id Add primary key constraint and automatic growth
NAME VARCHAR(20)
);
-- Delete auto growth
ALTER TABLE stu2 MODIFY id INT;
-- Add autogrow
ALTER TABLE stu2 MODIFY id INT AUTO_INCREMENT;
SELECT *FROM stu2;
INSERT INTO stu2 VALUES(NULL,'bbb'); -- Automatic growth is only related to the previous line
2.4 Foreign key constraints

-- Solution : Divide into two tables
-- Create department table (id,dep_name,dep_location)
-- a party , Main table
CREATE TABLE department(
id INT PRIMARY KEY AUTO_INCREMENT,
dep_name VARCHAR(20),
dep_location VARCHAR(20)
);
-- Create an employee table (id,name,age,dep_id)
-- In many ways , From the table
CREATE TABLE employee(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
age INT,
dep_id INT, -- The foreign key corresponds to the primary key of the primary table
CONSTRAINT emp_dept_fk FOREIGN KEY (dep_id) REFERENCES department(id)
);
-- Add two departments
INSERT INTO department VALUES (NULL,' R & D department ',' Guangzhou '),(NULL,' The sales department ',' Shenzhen ');
-- Add employees ,dep_id Indicates the employee's Department
INSERT INTO employee (NAME,age,dep_id) VALUES (' Zhang San ',20,1);
INSERT INTO employee (NAME,age,dep_id) VALUES (' Li Si ',21,1);
INSERT INTO employee (NAME,age,dep_id) VALUES (' Wang Wu ',20,1);
INSERT INTO employee (NAME,age,dep_id) VALUES (' Lao Wang ',20,2);
INSERT INTO employee (NAME,age,dep_id) VALUES (' King ',22,2);
INSERT INTO employee (NAME,age,dep_id) VALUES (' Xiao Wang ',18,2);
SELECT * FROM employee;
-- Delete foreign key
ALTER TABLE employee DROP FOREIGN KEY emp_dept_fk;
-- Add foreign keys
ALTER TABLE employee ADD CONSTRAINT emp_dept_fk FOREIGN KEY (dep_id) REFERENCES department(id)
2.4 Foreign key constraints – Cascade operation

-- ON UPDATE CASCADE update cascade
-- ON DELETE CASCADE cascading deletion
-- Delete foreign key
ALTER TABLE employee DROP FOREIGN KEY emp_dept_fk;
-- Add foreign keys Set cascading updates
ALTER TABLE employee ADD CONSTRAINT emp_dept_fk FOREIGN KEY
(dep_id) REFERENCES department(id) ON UPDATE CASCADE;
-- Add foreign keys Set cascading updates cascading deletion
ALTER TABLE employee ADD CONSTRAINT emp_dept_fk FOREIGN KEY
(dep_id) REFERENCES department(id) ON UPDATE CASCADE ON DELETE CASCADE;
3、 ... and 、 Relationships between multiple tables
3.1 Introduction to multi table relationship

3.2 One to many relationship implementation


3.3 Many to many relationship implementation


3.4 One to one relationship

3.5 Multi table relation cases
-- Create a travel route classification table tab_category
-- cid Classification of tourist routes , Automatic growth
-- cname Tourism route classification name is not empty , only , character string 100
CREATE TABLE tab_category(
cid INT PRIMARY KEY AUTO_INCREMENT,
cname VARCHAR(100) NOT NULL UNIQUE
);
Create travel itineraries tab_route
/* rid Tourist routes , Automatic growth rname The name of tourist route is not empty , only , character string 100 price Price rdate Practice on shelves , The date type cid Foreign keys , Classification */
CREATE TABLE tab_route(
rid INT PRIMARY KEY AUTO_INCREMENT,
rname VARCHAR(100) NOT NULL UNIQUE,
price DOUBLE,
rdate DATE,
cid INT,
FOREIGN KEY (cid) REFERENCES tab_category(cid)
);
/* Create a user table tab_user uid With the head of the household key , Self growth username User name length 100, only , Non empty password Password length 30, Non empty name Real name length 100 birthday Birthday sex Gender telephone cell-phone number , character string 11 email mailbox , String length 100 */
CREATE TABLE tab_user(
uid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(100) NOT NULL UNIQUE,
PASSWORD VARCHAR(30) NOT NULL,
NAME VARCHAR(100),
birthday DATE,
sex CHAR(1) DEFAULT ' male ',
telephone VARCHAR(11),
email VARCHAR(100)
);
/* Create a collection table tab_favorite rid Travel routes id, Foreign keys date Collection practice uid user id, Foreign keys rid and uid Can't repeat , Set the composite key , The same user cannot collect the same line twice */
CREATE TABLE tab_favorite(
rid INT,-- line id
DATE DATETIME,
uid INT, -- user id
-- Create composite keys
PRIMARY KEY(rid,uid), -- Combined the primary key
FOREIGN KEY (rid) REFERENCES tab_route(rid),
FOREIGN KEY (uid) REFERENCES tab_user(uid)
);

Four 、 normal form
4.1 Paradigm overview

4.2 Detailed explanation of three paradigms

The problem is :
1. There is very serious data redundancy ( repeat ): full name 、 Department name 、 Department of Wang Ren
2. There is a problem adding data : When adding a new department and Dean , Illegal data
3. There is a problem with data deletion : Zhang Wuji graduated , Delete data , The data of the system - Delete... Together .
After using the second paradigm to solve the problem 
Following the third paradigm , All the problems have been solved 

5、 ... and 、 Restore and backup of database
5.1 Command line / Graphical tool backup

边栏推荐
- 深度学习:GAN优化方法-DCGAN案例
- Mybtis-Plus常用的内置方法
- Meituan Er Mian: why does redis have sentinels?
- MySQL学习 Day3 多表查询 / 事务 / DCL
- JDBC学习 Day1:JDBC
- Guoju spent $1.8 billion to acquire its competitor KEMET, and the transaction may be completed in the second half of next year
- MySQL学习 Day2 排序查询 / 聚合函数 /分组查询 /分页查询 /约束/多表之间的关系
- 文件路径读取
- Is it difficult to operate email safely? COREMAIL joins hands with cloud store to create a new ecosystem of corporate email office!
- 2021.8.7笔记 servlet
猜你喜欢

深度学习-视频行为识别:论文阅读——双流网络(Two-stream convolutional networks for action recognition in videos)

3. Opencv geometric transformation
![[mit 6.s081] LEC 3: OS organization and system calls notes](/img/34/073d00245eb39844bbe1740f65fe07.png)
[mit 6.s081] LEC 3: OS organization and system calls notes

深度学习:GCN图分类案例
![[mit 6.s081] LEC 10: multiprocessors and locking notes](/img/62/ca6362830321feaf450865132cdea9.png)
[mit 6.s081] LEC 10: multiprocessors and locking notes

Random talk on GIS data (V) - geographic coordinate system

C杂讲 链表初讲

Deep learning: Gan case exercise -minst handwritten digits

数据库的常用命令2

Binary tree concept
随机推荐
Lotcode dynamic array exercise (724118766)
The first PCIe 5.0 SSD master of Jiangsu Huacun: TSMC 12NM process, mass production in 2020
Zhanrui fresh seedlings: enable full scene applications, and massive data needs the integration of AI and IOT
数据库的常用命令1
Uniapp has no effect on the page selector on the app side
rsa加解密(兼容微信小程序环境)
2021.7.19笔记 DML
On model training and reasoning of AI deep learning
MySQL学习 Day3 多表查询 / 事务 / DCL
1. OpenCV image basic operation
[MIT 6.S081] Lab 9: file system
"Who is Huawei" documentary film series landing on BBC: exposing a large number of Ren Zhengfei's unknown experience
Dynamic linked list 4 one-way circular linked list (loopsingle Implementation)
@Considerations for query of convert annotation in JPA
2021.8.1笔记 数据库设计
Please ask the great God a question, flinkcdc, the datetime field in synchronous MySQL will become a timestamp. Has anyone ever encountered it
2021.8.9笔记 request
Jrs-303 usage
Super practical! After reading the kubernetes study notes hidden by Alibaba P9, call NB directly
2021.7.22 note constraints