MySQL8.0 SQL (DQL) single table, multi-table query (detailed review)

Today's focus: DQL and learning points and practice environment description

               DQL is a data query language for querying data, and it is the one we use most in real development. And our project uses the most queries. In SQL, DQL has the largest proportion and the most complex structure.

Software used in this chapter:

        MySQL8.0.28(linux)

        Navicat 15 Database Remote

        Official practice database table: world.sql This table is a practice table, the data is definitely not accurate, please know

Description of learning environment:

world database
city city table (first table)
country country table (second table)
countrylanguage country language (third table)

View the table structure:

desc + table name

View the city table structure

desc city;  

Detailed table structure:

ID: city serial number (1-...)
name: city name
countrycode: country code, for example: CHN, USA
district: region: China province, America
population: population

Personal website address without any bad inducement 

This chapter mysql practice library table sql download: If you find it troublesome to watch, the teaching video I talked about is also in the website, you can directly download the world.sql practice library table and Navicat 15 database remote link software (permanent activation) download address https://www .bdqn.vip/download_one/

How to use: After importing world.sql to / (under the root directory)  , after logging in to the database

Import library table command:

source /world.sql

Table of contents

select general syntax and conditions

Conditional query of query statement

All writing methods of WHERE condition plus example demonstration

1. where with comparison judgment query

2. The logical connector (and or) of where

 3. BETWEEN of where conditional filtering 

Four, fuzzy query where

Aggregation functions, grouping, deduplication

One, count statistics

 Two, SUM summation

 3. MAX

 4. ORDER BY sorting, GROUP BY grouping (with aggregation function (MAX))

5. The minimum value of min

6. Average AVG

Seven, DISTINCT deduplication

HAVING Filters various data into groups

HAVING used with WHERE 

LIMIT offset

UNION and UNION ALL combine queries

Multi-table joint query 

INNER JOIN inner connection

 LEFT JOIN left connection

 RIGHT JOIN right join

 The JOIN link is directly written, and the default is an inner connection

A slightly difficult example of multi-table join query

        Expand knowledge points:

special query method


select general syntax and conditions

select + 列   
from  +表   
where +条件   满足条件查

group by+  条件 分组查询
having  + 条件 排序 或者过滤
order by +条件 排序
limit+ 不显示所有 显示前几 select * from 表名 limit 3;显示前三行

Conditional query of query statement

All writing methods of WHERE condition plus example demonstration

1. where with comparison judgment query

> greater than, < less than, >= greater than or equal to, <= less than or equal to, <> not equal to 

1. Query all cities and populations in China

SELECT `Name`,Population from city WHERE CountryCode="CHN";

search result:

2. Query the name and population of cities with a population of less than 100 people in the world

SELECT `Name`,Population FROM city WHERE Population<100;

search result:

Adamstown has a population of less than 42

 

 3. Display all other countries except the United States ( reverse )

SELECT * FROM city WHERE CountryCode<>"USA";

Query results: The results do not include the rest of the USA. Note that it is not recommended to use * in the actual environment, and it is easy to get stuck

All > is greater than, < is less than, >= is greater than or equal to, <= is less than or equal to, <> is not equal to the same as above, so we will not demonstrate them one by one

2. The logical connector (and or) of where

1. Query cities with a population greater than 8 million in China

Note that the connector AND means that both conditions before and after must be satisfied

SELECT
	`Name`,
	Population 
FROM
	city 
WHERE
	CountryCode = "CHN" 
	AND Population > 8000000;

 search result:

2. Query the cities and populations of all China and Russia

Note that the link symbol or indicates that one of the two conditions before and after can be displayed

SELECT
	`Name`,
	CountryCode,
	Population 
FROM
	city 
WHERE
	CountryCode = "CHN" 
	OR CountryCode = "RUS";

search result:

 3. BETWEEN of where conditional filtering 

BETWEEN between what and what, the intermediate link symbol is AND

1. Query the names of all cities with a population between 5 million and 6 million

SELECT
	`Name`,
	CountryCode,
	Population 
FROM
	city 
WHERE
	Population BETWEEN 5000000 
	AND 6000000;

search result:

Of course, this BETWEEN does not limit the number of people, and you can also query the time

 The time is not in the table of this exercise. I made a table at random for demonstration. In order to let everyone better understand

query by date

2. All data between 2022-01-01 and 2022-03-31 

SELECT
	Start_docking_time #字段名
FROM
	app_handoverinfo  #表名
WHERE
	Start_docking_time BETWEEN "2022-01-01"   #查询所有 今年 1月份到3月份所有的时间
	AND "2022-03-31";

search result:

Four, fuzzy query where

 LIKE fuzzy query keyword % represents all characters

Note: Do not appear similar to %CH%, with percent signs before and after, because the performance is extremely poor without indexing 

1. Query the city information starting with CH in the country

SELECT
	* 
FROM
	city 
WHERE
	CountryCode LIKE "CH%";  

search result:

Aggregation functions, grouping, deduplication

#-------------聚合函数关键字-------------------
SUM #求和
AVG #平均值
COUNT #统计
MAX #最大值
MIN #最小值
#-------------条件分组关键字-------------------
GROUP BY #分组 
#-------------去重关键字-----------------------
DISTINCT #去重
#--------------排序关键字----------------------
ORDER BY

One, count statistics

Remember that statistics need to be used together with grouping, otherwise an error will be reported

1. Count how many cities there are in China

SELECT
	CountryCode,
	COUNT( `Name` ) 
FROM
	city 
WHERE
	CountryCode = "CHN" 
GROUP BY   
	CountryCode;

search result:

 Two, SUM summation

1. Query the total number of all populations in China

SELECT
	CountryCode,
	SUM( Population ) 
FROM
	city 
WHERE
	CountryCode = "CHN";

search result:  

 3. MAX

1. Query the value of the largest population in China

SELECT MAX(Population) FROM city WHERE CountryCode="CHN";

 search result:

 4. ORDER BY sorting, GROUP BY grouping (with aggregation function (MAX))

Note that ORDER BY plus desc is descending order (default ascending order)

 2. Query China, the most populous place in the region (the maximum value of each group can be obtained through group by grouping)

Can be used as a sorting condition for ORDER BY 

LIMIT show first few

SELECT
	District,#地区
	MAX( Population ) #人口最大	
FROM
	city 
WHERE
	CountryCode = "CHN" 
GROUP BY
	District 
ORDER BY
	MAX( Population ) DESC 
LIMIT 1;#只显示第一个

search result:

5. The minimum value of min

1. Query the value with the smallest population in China

SELECT MIN(Population) FROM city;


search result:

2. Query China, the place with the least population in the region (the minimum value of each group can be obtained by group by grouping)

Can be used as a sorting condition for ORDER BY 

SELECT
	District, #地区
	MIN( Population ) #人口最小
FROM
	city 
WHERE
	CountryCode = "CHN"  #条件中国
GROUP BY
	District  #按省分组
ORDER BY
	MIN(Population);  #按最小值排序

search result:

6. Average AVG

1. Query the average value of China's total population

SELECT
	AVG( Population ) 
FROM
	city 
WHERE
	CountryCode = "CHN";

 search result:

Seven, DISTINCT deduplication

1. Count the number of each country and region through DISTINCT to remove duplicates with the same name and only keep one

SELECT
	countrycode,
	COUNT( DISTINCT district ) 
FROM
	city 
GROUP BY
	countrycode;

 search result:

2. Query all regions in China and deduplicate

DISTINCT can also be written separately

SELECT DISTINCT
	District 
FROM
	city 
WHERE
	CountryCode = "CHN";

search result:

HAVING Filters various data into groups

First of all, the difference between HAVING and WHERE:

   1. The where clause filters records before aggregation, that is to say, it acts before the group by and having clauses. Whereas the having clause filters the group records after aggregation.

   2. Aggregation functions cannot be used in where, and aggregation functions can be used in having 

    For example: SELECT Population FROM city WHERE SUM(Population) > 8000000; wrong wording

To put it simply, where is directly performed on the data in the table, while HAVING is based on preconditions for conditional judgment

  3. It can be used in conjunction with where, and the effect is not too fancy~~~ Hahaha~~

Example:

  1. Count the total population of all countries, filter out those with a total population greater than 8000w, and arrange them in descending order

SELECT
	CountryCode,  #国家名字中
	SUM( Population )  #统计人口
FROM
	city  
GROUP BY
	CountryCode 
HAVING
	SUM( Population ) > 80000000  #条件,切记需要前置有 才可用 having
ORDER BY
	SUM( Population ) DESC #按人口总数降序

search result:

HAVING used with WHERE 

It's not very useful, it's just bells and whistles, it looks like the code is so complicated hahaha~~~

SELECT
	District,
	SUM( Population ),
	COUNT(*) 
FROM
	city 
WHERE
	CountryCode BETWEEN "CHN" 
	AND "RUS" 
GROUP BY
	District
HAVING
	COUNT(*) > 40
ORDER BY
	SUM( Population ) DESC

search result:

LIMIT offset


LIMIT M, N: Skip M lines, display a total of N lines
LIMIT Y OFFSET X: Skip X lines, display a total of Y lines

1. Query that the total population of the country is greater than 50 million and in descending order, display the first three offsets

SELECT
	CountryCode, #国家缩写
	SUM( Population )  #统计人口总数
FROM
	city 
GROUP BY
	CountryCode #按国家分组
HAVING
	SUM( Population ) > 50000000  #查询大于5000万的
ORDER BY
	SUM( Population ) DESC  #按总数降序
	LIMIT 3 OFFSET 1; #显示前三,并向后偏移一位

search result:

 2. The second implementation method of offset

SELECT
	CountryCode,
	SUM( Population ) 
FROM
	city 
GROUP BY
	CountryCode 
HAVING
	SUM( Population ) > 50000000 
ORDER BY
	SUM( Population ) DESC 
	LIMIT 1,3;  ##这里注意 1 代表跳过第一行  3 代表只显示三行

Consistent with the above query results

UNION and UNION ALL combine queries

Note :

        UNION combined query results do not remove duplicates

        UNION ALL combined query results to remove duplicates

        An error will be reported if the number of fields of the union is inconsistent

1. Query all information about China or Russia

        Several writing methods have the same effect, for comparison

The first way of writing where

SELECT
	* 
FROM
	city 
WHERE
	CountryCode = "CHN" 
	OR CountryCode = "RUS";

The second way of writing UNION

SELECT * FROM city WHERE countrycode='CHN'
UNION ALL ##将两条语句链接并去重  不加all 就是不去重
SELECT * FROM city WHERE countrycode='RUS';

search result:

Multi-table joint query 

JOIN can be divided into the following three categories according to the function:
INNER JOIN (inner connection, or equivalent connection): to obtain the records of the field matching relationship in the two tables;
LEFT JOIN (left connection): to obtain all records in the left table, even in The right table has no corresponding matching records, and it is empty NULL;
RIGHT JOIN (right connection): Contrary to LEFT JOIN, it is used to obtain all records in the right table, even if the left table has no corresponding matching records.

Direct JOIN defaults to internal links

Contents of the practice table: Let’s take a look at the difference between the links first.  AS is an alias ##This table is not in the world library. After everyone understands the writing method, practice by yourself

Two tables, one student table (student) and one grade table (score) are listed together as student number (code)

INNER JOIN inner connection

        Match the content in both tables, and do not display the unmatched ones

SELECT * FROM student as a INNER JOIN score AS b ON a.`code`=b.`code`; 

search result:

 LEFT JOIN left connection

        The right table (score) matches the content of the left table (student), if there is no content in the right table, it will be displayed as empty

SELECT * FROM student as a LEFT JOIN score AS b ON a.`code`=b.`code`; 

 RIGHT JOIN right join

        The left table (student) matches the content of the right table (score), and only those in the right table are displayed, and those not in the right table are not displayed

SELECT * FROM student as a RIGHT JOIN score AS b ON a.`code`=b.`code`;

search result:

 The JOIN link is directly written, and the default is an inner connection

SELECT * FROM student as a JOIN score AS b on a.`code`=b.`code`; 

search result:

1. Query Zhao Si's math results

#a 代表 学生名字表
#b 代表 学生成绩表

SELECT
	a.`name`,  
	b.class,
	b.score 
FROM
	student AS a
	JOIN score AS b ON a.`code` = b.`code`  #默认内连接
WHERE
	b.class = "数学"  #条件
	AND a.`name` = "赵四"; #条件

 search result:

A slightly difficult example of multi-table join query

Exercise sheet content:

List of student names (student) List of teacher names (teacher) Course schedule (course) Score sheet (score)              

 Query according to the above four tables

Expand knowledge points:

function illustrate
FLOOR(X)

Returns the largest integer not greater than X (in simple terms, rounding)

ROUND(X) Returns the nearest integer to X, rounding up when truncating (in simple terms, rounding up)
ROUND(X,D) Reserve the value of D digits after the decimal point of X, and round up when truncating. (Simply put, keep a few decimal places and round off the unreserved numbers)
FORMAT(X,D) Format the number X, keep X to D decimal places, and round up when truncating. (consistent with above)
CASE meet the conditions and return

Refer to the following for specific usage

1. Query and sort the student numbers and average grades of students whose average grade is greater than 70

Note that a new function FLOOR is used below to discard the digits after the decimal point and only keep integers

SELECT
	a.sname,  #学生名字
	FLOOR(AVG( b.score ))  学生平均成绩  
FROM
	student AS a
	LEFT JOIN score AS b ON a.sno = b.sno  
	#将共同列链接
GROUP BY
	a.sname   #以名字分组 
HAVING
	AVG( b.score )> 70  #平均成绩大于70 
ORDER BY
	AVG( b.score ) DESC; #降序排序

operation result:

 2. Query the names of students who have only taken one course

Idea: Connect multiple tables --- set alias --- find key fields --- deduplicate by name --- count how many courses there are --- and query for less than two courses

SELECT DISTINCT  #DISITNCT 去重
	s.sname,
	COUNT( c.cname ) #统计课程名字 
FROM
	student AS s
	JOIN score AS sc ON s.sno = sc.sno  #将三表连起来
	JOIN course AS c ON sc.cno = c.cno 
GROUP BY
	s.sname 
HAVING
	COUNT( c.cname )< 2; #小于2的全部显示出来

 search result:

 3. Query the names, student numbers, subjects, grades, and subject teacher names of students whose scores are less than 60

SELECT
	s.sname, #学生名字
	s.sno,   #学号
	c.cname, #科目名字
	sc.score, #成绩
	t.tname   #老师名字
FROM
	student AS s  #将四表连起来
	JOIN score AS sc ON s.sno = sc.sno
	JOIN course AS c ON sc.cno = c.cno
	JOIN teacher AS t ON c.tno = t.tno 
WHERE
	sc.score < 60; #成绩低于60的

 search result:

4. Query the grades of each course. Students with scores greater than 85 are excellent, good (71-85), fair (60-70), and failing (less than 60), and sorted by student number

Idea: Now connect all the tables to check, find out the key fields you want, without adding any conditions, check it, and then write a judgment statement according to the CASE function

SELECT
	s.sno,
	s.sname,
	c.cname,
	sc.score,(
	CASE
			
			WHEN sc.score > 85 THEN
			"优秀" 
			WHEN sc.score < 85 AND sc.score > 71 THEN
			"良好" 
			WHEN sc.score BETWEEN 60 
			AND 70 THEN
				"勉强及格" ELSE "不及格" 
			END 
			) 
		FROM
			student AS s
			JOIN score AS sc ON s.sno = sc.sno
			JOIN course AS c ON sc.cno = c.cno
			JOIN teacher AS t ON c.tno = t.tno 
		ORDER BY
		s.sno;

 search result:

special query method

1. Query the installation location of MySQL

select @@basedir;

2. Query port number

select @@port;

3. Fuzzy view the configuration at the beginning of innodb

show variables like 'innodb%';

4. Query the current system time

select now();

Guess you like

Origin blog.csdn.net/weixin_58279299/article/details/125516232