MySQL Query Statement Encyclopedia

Table of contents

basic query

direct query

AS is aliased

Deduplicate (repeated) query

conditional query

arithmetic operator query

logical operator query

Regular expression query ⭐

fuzzy query

range query

Whether it is not empty judgment query

Sort query

 Limit query (paging query)

random query

Group query

HAVING

Advanced Search

subqueries (nested queries)

row number

 ranking

 aggregate function

connection query

inner join

outer join

Full outer join (composition)

​edit

cross connect

The order in which the SELECT clauses must follow


basic query

direct query

query all columns

语法:select * from 表名;
-- 查询 student 表中所有内容
select * from student;

Query the specified column

语法:select 字段 from 表名;
-- 查询 student 表中的name列 与 age列
select name, age from student;
AS is aliased

Use AS to alias fields

语法:select 字段 as 别名 from 表名;(as可省略)
-- 查询 student 表中的name列 与 age列
select name 名字, age 年龄 from student;
-- select name as 名字, age as 年龄 from student;

 Use AS to alias the table

语法:select 字段 from 表名 as 别名;
-- 查询 student 表中的name列 与 age列,同时给student起个‘学生年龄表’别名
select name 名字, age 年龄 from student 学生年龄表;
Deduplicate (repeated) query
DISTINCT 用于从表中获取不重复的数据
语法:select distinct 列名 from 表名;
-- 查询 student 表中所有的不同年龄
select distinct age from student;
conditional query
语法:select 字段 from 表名 where 条件;
-- 从 student 表中查询 age = 18 的 name
select name from student where age = 18;
arithmetic operator query
语法:>(大于), <(小于), =(等于), !=(不等于), <>(不等于), >=(大于等于), <=(小于等于)
-- 从 student 表中查询 age >=20 的所有记录
select * from student where age >= 20;
logical operator query
语法:and(且), or(或), not(非) sql 会首先执行 and 条件,再执行 or 语句。除非加括号
-- 从 student 表中查询 age >=20并且成绩高于50分的所有记录
select * from student where age >= 20 and score > 50;
-- 从 student 表中查询 age = 15 或 score = 70 的所有记录
select * from student where age = 15 or score = 70;
Regular expression query ⭐
正则表达式要用regexp
语法:select 字段 from 表名 where 字段 regexp '正则表达式';

--从 student 表中查询 name 含有李的所有记录
select * from student where name regexp '李';

--从 student 表中查询 name 含有李或三的所有记录
select * from student where name regexp '李|三';

--从 student 表中查询 name 为李开头的所有记录
select * from student where name regexp '^李';

--从 student 表中查询 name 为五结尾的所有记录
select * from student where name regexp '五$';

-- 字符.用来替代字符串中的任意一个字符
--从 student 表中查询 name 含'赵'和'真'两个字符且中间只隔了一个字符的所有记录
select * from student where name regexp '赵.真';

-- 字符*和+都可以匹配多个该符号之前的字符。不同的是,+表示至少一个字符,而*可以表示 0 个字符。
-- 从 student 表中查询 name 含丰字的所有记录(三*表示丰字前面可以有0-无数个三,因此至少含有丰)
select * from student where name regexp '三*丰';
-- 从 student 表中查询 name 含丰且前面只少有一个三的所有记录(三+表示丰字前面至少个三,因此至少含有三丰)
select * from student where name regexp '三+丰';


-- 从 student 表中查询 name 包含李、三、 真 3 个字符中任意一个的记录
select * from student where name regexp '[李三真]';
-- 方括号[ ]还可以指定集合的区间。例如,“[a-z]”表示从 a~z 的所有字母;“[0-9]”表示从 0~9 的所有数字;“[a-z0-9]”表示包含所有的小写字母和数字;“[a-zA-Z]”表示匹配所有字符;“[\\u4e00-\\u9fa5]”表示中文汉字

-- [^字符集合]用来匹配不在指定集合中的任何字符。
-- 查询 name 字段值包含字母 a~t 以外的字符的所有记录
select * from student where name regexp'[^a-t]';

-- 字符串{n,}表示字符串连续出现 n 次;字符串{n,m}表示字符串连续出现至少 n 次,最多 m 次。
-- a{2,} 表示字母 a 连续出现至少 2 次,也可以大于 2 次;a{2,4} 表示字母 a 连续出现最少 2 次,最多不能超过 4 次。
-- 查询 name 字段值出现字母‘e’ 至少 2 次的记录
select * from student where name regexp'e{2,}';

 Commonly used matching methods in the REGEXP operator

options illustrate example Example match value
^ start character of matching text '^b' matches a string starting with the letter b book、big、banana、bike
$ Matches the end character of the text 'st$' matches strings ending with st test、resist、persist
. matches any single character 'b.t' matches any character between b and t bit、bat、but、bite
* matches zero or more of the characters preceding it 'f*n' matches character n preceded by any character f fn、fan、faan、abcn
+ Matches the preceding character 1 or more times 'ba+' matches a b followed by at least one a ba、bay、bare、battle
<string> matches text containing the specified characters 'fa' matches text containing 'fa' fan、afa、faad
[character set] matches any character in the character set '[xz]' matches x or z dizzy、zebra、x-ray、extra
[^] matches any character not in parentheses '[^abc]' matches any string that does not contain a, b or c desk、fox、f8ke
string{n,} Matches the preceding string at least n times 'b{2}' matches 2 or more b bbb、bbbb、bbbbbbb
string{n,m} Match the preceding string at least n and at most m times 'b{2,4}' matches at least 2 and at most 4 b bbb、bbbb
fuzzy query
语法:select 字段 from 表名 where 字段 like '%数据%';
-- 从 student 表中查询 name 中含有 '张' 的所有记录
select * from student where name like '%张%';
-- 从 student 表中查询 name 中姓 '张' 的所有记录
select * from student where name like '张%';
range query
 in与not in     between … and …:范围连续(包含端点)

语法:select 字段 from 表名 where 字段 in(列表)//或 not in(列表);
-- 从 student 表中查询 age 为 (18, 19, 20) 之间的所有记录
select * from student where age in(18, 19, 20);
-- 从 student 表中查询 除了age 为 (18, 19, 20) 之间的所有记录
select * from student where age not in(18, 19, 20);

语法:select 字段 from 表名 where 字段 between 值1 and 值2;
-- 从 student 表中查询 age 为 (18, 19, 20) 之间的所有记录
select * from student where age between 18 and 20;
Whether it is not empty judgment query
null(为空)  not (非空) 判断是否为空要用is
语法:select 字段 from 表名 where 字段 is null(not null);
--从 student 表中查询 age 未填写(为空)的所有记录
select * from student where age is null;

priority

The order of priority from high to low is: parentheses > NOT > comparison operator > logical operator

AND is operated before OR, if it appears at the same time and you want to calculate or first, you need to use it in combination with ()

Sort query
语法:select 字段 from 表名 order by 字段 排序方式(升序 asc, 降序 desc);
-- 从 student 表中查询所有记录并按照 age 升序排序
select * from student order by age asc;

进阶 select 字段 from 表名 order by 字段 排序方式,字段 排序方式;
(当第一个字段相同时,按第二个字段排序顺序来)
-- 从 student 表中查询所有记录并按照 age 升序,当 age 相同时,按score降序排序
select * from student order by age asc,score desc;

 Limit query (paging query)
语法:limit可以限制制定查询结果的记录条数
    注意  0 表示第一行记录,也是从 0 开始
    select 字段 from 表名 limit n;查询前n行的记录
	select 字段 from 表名 limit n, m;查询第n+1行到第m+n行的记录(也就是从第n+1行开始查询m行记录)

-- 从 student 表中查询第三行到第六行的记录,也就是第三行开始查询4条记录
select * from student limit 2, 4;

random query
-- 随机显示两个学生信息
select * from student order by rand() limit 2;
Group query
语法:select 字段 from 表名 group by 字段 ;
-- 从 student 表中查询age值和每个age都有多少人
select age ,count(*) from student group by age ;

 The GROUP BY clause must appear after the WHERE clause and before the ORDER BY clause

HAVING

The HAVING statement is used to filter (filter) the grouped data

语法:select 字段 from 表名 group by 字段 having 条件;
-- 从 student 表中查询age>19值和每个age>19都有多少人
select age ,count(*) from student group by age having age > 19;

Advanced Search

subqueries (nested queries)

In a select statement, another select statement is embedded, the embedded select statement is called a subquery statement, and the external select statement is called a main query.

Relationship between main query and subquery

  • A subquery is embedded in the main query
  • Subqueries are auxiliary to the main query, either as conditions or as data sources
  • A subquery is a statement that can exist independently and is a complete select statement
语法:语法:嵌套查询也就是在查询语句中包含有子查询语句,所以叫嵌套查询,没有单独的语法,嵌套子查询通常位于查询语句的条件之后;

-- 先查询学生平均年龄,再查询大于平均年龄的学生
select * from student where age > (select avg(age) from student);
row number
-- row_number() over (排序语句)
-- row_number()从1开始,为每一条分组记录返回一个数字

-- 查询名次 姓名 成绩
select row_number() over (order by score desc) 名次,name 姓名,score 成绩 from student;

 ranking

DENSE_RANK() is a window function that assigns a rank to each row in a partition or result set without gaps in the rank values.

  • DENSE_RANK(). If you use DENSE_RANK() for ranking you will get: 1,1,2,3,4.
  • RANK(). If you use RANK() for ranking, you will get: 1, 1, 3, 4, 5.
  • ROW_NUMBER(). If you use ROW_NUMBER() for ranking you get: 1, 2, 3, 4, 5. (usually used for numbering)
-- 排名
--排名并列后面名次挨着
select id 编号,name 姓名,score 分数,concat('第',dense_rank() over (order by score
desc),'名') 名次 from student;

--排名并列后面名次不挨着
select id 编号,name 姓名,score 分数,concat('第',rank() over (order by score
desc),'名') 名次 from student;
 aggregate function
-- 聚合函数
-- 可以实现一些具体的功能,比如找最小值,找最大值,求和,计数等

-- min() 求最小值
语法:select min(字段) from 表名;
-- 从 student 中查询最小的 age
select min(age) from student;

-- max() 求最大值
语法:select max(字段) from 表名;
-- 从 student 中查询最大的 age
select max(age) from student;


-- sum() 求和
语法:select sum(字段) from 表名;
-- 从 student 中统计所有 age 的和
select sum(age) from student;


-- avg() 求平均值
语法:select avg(字段) from 表名;
-- 从 student 中对所有的 age 求平均值
select avg(age) from student;


-- count(字段) 统计个数
语法:select count(字段) from 表名;
-- 从 student 中查询 name 的记录个数
select count(name) from student;
connection query

MySQL query joins are mainly divided into three categories: inner joins, outer joins, and cross joins.

inner join

INNER JOIN

Inner join means that the records in two or more tables have a corresponding relationship, which can be represented by primary key and foreign key. Inner joins return results by retaining the same records. That is, query results are returned only if matching records exist in both tables.

-- 内连接
语法:select 字段 from 表1 inner join 表2 on 表1.字段 = 表2.字段;
	根据两个表中共有的字段进行匹配,然后将符合条件的合集进行拼接
	on后面是连接条件,也就是共有字段

select * from student inner join engScore on student.name = engScore.name;
-- 将 student 表与 engScore 表通过相同的 name 拼接起来,简单的来说就是两个 excel 合并

Example Assuming we have two tables student and course, their columns and contents are as follows

student table:

id name age
1 Jack 18
2 Tom 19
3 Jerry 20
4 Bob 18

course table:

course_id course_name student_id
1 Math 1
2 English 2
3 Science 2
4 History 3

Now we want to query the courses selected by each student, we can use the following SQL statement:

SELECT student.name, course.course_name
FROM student
INNER JOIN course
ON student.id = course.student_id;

This query will return the following results:

name course_name
Jack Math
Tom English
Tom Science
Jerry History
outer join

OUTER JOIN

The outer keyword can be omitted for outer joins

Outer joins are divided into left joins and right joins. This kind of join means that when two or more tables are joined, all records are included.

left (outer) join

A left join means that the left table fetches all records, and the right table fetches only matching records. If the left table has no matching records with the right table, the right table will return a NULL value.

-- 左连接
语法:select 字段 from 表1 left join 表2 on 连接条件;

select * from student left join engScore on student.name = engScore.name;
-- 与内连接形式相同,但左表为主表,指定字段都会显示,右表为从表,无内容会显示 null

example

Still taking the above student table and course table as an example, if we want to query the courses selected by each student, including those students who have not selected courses. The following SQL statements can be used:

SELECT student.name, course.course_name
FROM student
LEFT JOIN course
ON student.id = course.student_id;

This query will return the following results:

name course_name
Jack Math
Tom English
Tom Science
Jerry History
Bob NULL

right (outer) join

A right join is similar to a left join, except that the roles of the left and right tables are reversed

-- 右连接
语法:select 字段 from 表1 right join 表2 on 连接条件;

select * from student right join engScore on student.name = engScore.name;
-- 与内连接形式相同,但右表为主表,指定字段都会显示,左表为从表,无内容会显示 null

Continuing to use the above student table and course table as an example, if we want to query the students of each course, including the students who did not choose the course. The following SQL statements can be used:

SELECT student.name, course.course_name
FROM student
RIGHT JOIN course
ON student.id = course.student_id;

This query will return the following results:

name course_name
Jack Math
Tom English
Tom Science
Jerry History
NULL Geography
Full outer join (composition)

In SQL, there is also a FULL OUTER JOIN (full outer join), but MySQL does not support it. Therefore, we can simulate a full outer join through the UNION statement.

union and union all

Union will deduplicate. If it is returned in one condition, it will not be returned even if it is in the next condition. Union all will not remove duplicates. If it is returned in one condition, it will also be returned if there is a duplicate in the next one.

 select id, name, age from s1 where age >18union select id, name, agefrom s2 where age >18;
-- 查询s1和s2中所有年纪大于18的学生的id,name,age,并将结果放在一个表中,同时去掉重复

 

cross connect

CROSS JOIN

A cross join is a join without any join condition between two or more tables. In simple terms, a cross join allows you to query for all possible combinations.

tb1:

d name
1 A
2 B
3 C

We can use the following SQL statement to perform a cross join:

SELECT t1.name, t2.name
FROM tb1 t1
CROSS JOIN tb1 t2;

search result

name name
A A
A B
A C
B A
B B
B C
C A
C B
C C

The order in which the SELECT clauses must follow

clause illustrate Is it necessary to use
SELECT the column or expression to return yes
FROM the table to retrieve data from Only used when selecting data from a table
WHERE row-level filtering no
GROUP BY group description Only used when computing aggregates by group
HAVING group level filtering no
ORDER BY output sort order no
LIMIT the number of rows to retrieve no

Guess you like

Origin blog.csdn.net/qq_57570052/article/details/132171270