Basic query statement of MySQL database (DQL data query statement)

Table of contents

1. Query conditions

(1) where child clause

(2) like fuzzy query

2. Query result processing

(1) Set the query column

(2) Calculation of columns

(3) The as field takes an alias

(4) distinct Eliminate duplicate lines

(5) function

(6) Group query group by

(7) Sorting - order by

(8) Page query - limit


The basic query syntax of the database: extract the statement that satisfies certain conditions from the data table (single table/multiple tables) as the query statement.

The basic query syntax is as follows:

select 结果显示语句 from 需要查询的表 where 查询条件语句 结果处理语句;

The basic query statement is presented in the form of select ... from .... where .... This article mainly talks about the result display statement, query condition statement, and result processing statement.

1. Query conditions

(1) where child clause

Where clause: A where clause (condition) can be added after the delete, modify, and query statements to filter the data that meets the specified requirements for deletion, modification, and query operations. Therefore, the where clause is the top priority in all operations of the database.

#删除
delete from tableName where conditions;
#修改更新
update tabeName set ... where conditions;
#查询
select .... from tableName where conditions;

Where is followed by a selection conditional statement, and the conditional statement is a conditional selection through conditional relational operators and logical relational operators.

Conditional relational operators:

## = 等于。
select * from stus where stu_num = '20210101';

## != <> 不等于。
select * from stus where stu_num != '20210101';
select * from stus where stu_num <> '20210101';

## > ⼤于。
select * from stus where stu_age>18;

## < ⼩于。
select * from stus where stu_age<20;

## >= ⼤于等于。
select * from stus where stu_age>=20;

## <= ⼩于等于。
select * from stus where stu_age<=20;

## between and 区间查询 between v1 and v2 [v1,v2],含有左右数值。
select * from stus where stu_age between 18 and 20;

Logical relational operators:

## and 并且 筛选多个条件同时满⾜的记录
select * from stus where stu_gender='⼥' and stu_age<21;

## or 或者 筛选多个条件中⾄少满⾜⼀个条件的记录
select * from stus where stu_gender='⼥' or stu_age<21;

## not 取反
select * from stus where stu_age not between 18 and 20;

(2) like fuzzy query

After where, in addition to simple relational operators, fuzzy matching can also be performed with like+fuzzy matching operators. In addition, there is a regular expression method for fuzzy matching. In the follow-up study, we will mention the usage of regular expressions separately.
Basic syntax:

select * from tableName where 列名 like 'reg';

The LIKE keyword supports the percent sign "%" and underscore "_" wildcards.

"%" is the most commonly used wildcard in MySQL, it can represent a string of any length, and the length of the string can be 0. For example, a%b means a character string of any length starting with the letter a and ending with the letter b. This string can represent strings such as ab, acb, accb, accrb, etc.

"_" can only represent a single character, and the length of a character cannot be 0. For example, a_bit can represent strings such as acb, adb, aub, etc.

Summarized as follows:

% means any number of characters [%o% contains the letter o]
_ means any character [_o% the second letter is o]
Example:

# 查询学⽣姓名包含字⺟o的学⽣信息
select * from stus where stu_name like '%o%';

# 查询学⽣姓名第⼀个字为`张`的学⽣信息
select * from stus where stu_name like '张%';

# 查询学⽣姓名最后⼀个字⺟为o的学⽣信息
select * from stus where stu_name like '%o';

# 查询学⽣姓名中第⼆个字⺟为o的学⽣信息
select * from stus where stu_name like '_o%';

2. Query result processing

The query result processing is divided into two parts, one is after the select, the result display statement before the from statement, at the same time, the result can also be processed here, and the aggregation function is used for calculation; the other is after the where conditional statement, the result is processed Sort, group.

(1) Set the query column

Setting the query column is to set the column you need to display the result after select and before from. columnname is the column name, and the number of column names is the number displayed. If the character * is filled in, the corresponding data of all columns in the query result will be displayed.

select columName1,columnName2,... from stus where stu_age>20;

(2) Calculation of columns

Computing data of a data type that matches a calculated column through mathematical operators is called column calculation, and the format is as follows:

## 出⽣年份 = 当前年份 - 年龄
select stu_name,2021-stu_age from stus;

(3) The as field takes an alias

The column name of the final display result we get through the query statement is often the original column name. When we need to modify the generated result column name to get the result table we want, we can assign it through as, of course, except as method, we can also rename it by space + alias. Of course, this method is also applicable to the assignment of table names in our subsequent multi-table joint query.

#我们可以为查询结果的列名 去⼀个语义性更强的别名 (如下案例中 as 关键字也可以省
略)
select stu_name,2021-stu_age as stu_birth_year from stus;

select stu_name as 姓名,2021-stu_age as 出⽣年份 from stus;

(4) distinct Eliminate duplicate lines

When we often query information in tables, duplicate values ​​will inevitably appear. For example, when querying age, people with age will appear. When we want to get the age value of the table, we can filter the results through the distinct statement.

select distinct stu_age from stus;

(5) function

① aggregate function

SQL provides some functions that can calculate the columns of the queried records - aggregate function
count: used for statistical counting

# 统计学⽣表中学⽣总数
select count(stu_num) from stus;

# 统计学⽣表中性别为男的学⽣总数
select count(stu_num) from stus where stu_gender='男';

max: used to find the maximum value of the numeric type

select max(stu_age) from stus;

min: used to find the minimum value of the numeric type

select min(stu_age) from stus where stu_gender='⼥';

sum: summation of data for numeric types

# 计算所有性别为男的学⽣的年龄的综合
select sum(stu_age) from stus where stu_gender='男';

avg: used to calculate the average number of data of numeric type

select avg(stu_age) from stus where stu_gender='男';

②Date function
When we add data to a column of date type, we can assign a value by string type (the format of the string must be
yyyy-MM-dd hh:mm:ss)
If we want to get the current system time and add it to For date type columns, you can use now() or sysdate().
For a database system, when operators insert data into the database, delete data, or update data, we all hope to know the time when the data was modified. The data operator is Who, so the date function can solve this problem very well, and can directly obtain the current system time.

# 通过now()获取当前时间
insert into
stus(stu_num,stu_name,stu_gender,stu_age,stu_tel,stu_qq,stu_enterence)
values('20210109','张⼩四','⼥',20,'13434343355','1233333',now());

# 通过sysdate()获取当前时间
insert into
stus(stu_num,stu_name,stu_gender,stu_age,stu_tel,stu_qq,stu_enterence)
values('20210110','李雷','男',16,'13434343366','123333344',sysdate());

③String function
Process strings through SQL commands.

concat() splicing function

# concat(colnum1,colunm2,...) 拼接多列

select concat(stu_name,'-',stu_gender) from stus;

 The upper() field value is changed to uppercase

# upper(column) 将字段的值转换成⼤写
select upper(stu_name) from stus;

 The upper() field value is changed to lowercase

# lower(column) 将指定列的值转换成⼩写
select lower(stu_name) from stus;

Substring() determines the display of the intercepted part in the column

# substring(column,start,len) 从指定列中截取部分显示 start从1开始
select stu_name,substring(stu_tel,8,4) from stus;

(6) Group query group by

Grouping: It is to group the records in the data table according to the specified class.
In the MySQL database query statement (DQL), there are strict order requirements for the grouping, selection, and sorting of the result set, and can only be written in the following order. Replacing the position will report an error.

select 分组字段/聚合函数
from 表名
[where 条件]
group by 分组列名 
[having 条件]
[order by 排序字段]

Notice:

①Use * after select to display the grouping of query results, then display the first record of each group (this display is usually
meaningless)
②Usually display grouping fields and aggregation functions after select (grouped data is grouped) Statistics, summation, average value, etc.)
statement execution attributes: first query records from the database according to where conditions! group by to group query records
#execute having to filter the grouped data
 

# 先对查询的学⽣信息按性别进⾏分组(分成了男、⼥两组),然后再分别统计每组学⽣的个数
select stu_gender,count(stu_num) from stus group by stu_gender;

 

# 查询所有学⽣,按年龄进⾏分组,然后分别统计每组的⼈数,再筛选当前组⼈数>1的组,再按
年龄升序显示出来
select stu_age,count(stu_num)
from stus
group by stu_age
having count(stu_num)>1
order by stu_age;

 

(7) Sorting - order by

Arrange the queried records that meet the conditions in ascending/descending order according to the value of the specified column. The sorting can be divided into single-field sorting and multi-field sorting.
The basic syntax for sorting is as follows:

select * from tableName where conditions order by columnName asc|desc;

order by columnName means to sort the query results according to the specified column
asc ascending order according to the specified column (default)
desc descending order according to the specified column

# 单字段排序
select * from stus where stu_age>15 order by stu_gender desc;

# 多字段排序 : 先满⾜第⼀个排序规则,当第⼀个排序的列的值相同时再按照第⼆个列的规则
排序
select * from stus where stu_age>15 order by stu_gender asc,stu_age desc;

 

(8) Page query - limit


When there are many records in the data table, if all of them are queried and displayed to the user at one time, the readability/ experience of the user will not be very good , so we can display the data in pages.

select ...
from ...
where ...
limit num1,num2
#①param1 int , 表示获取查询语句的结果中的第⼀条数据的索引(索引从0开始)
#②param2 int, 表示获取的查询记录的条数(如果剩下的数据条数<param2,则返回剩下
的所有记录)

example:

Display the student information in the data table in pages. There are 10 pieces of data in total, and we display 3 pieces on each page.
 

# 查询第⼀⻚:
select * from stus [where ...] limit 0,3; 

# 查询第⼆⻚:
select * from stus [where ...] limit 3,3;

# 查询第三⻚:
select * from stus [where ...] limit 6,3;

# 如果在⼀张数据表中:
# pageNum表示查询的⻚码
# pageSize表示每⻚显示的条数
# 通⽤分⻚语句如下:
select * from <tableName> [where ...] limit (pageNum-
1)*pageSize,pageSize;

 

Guess you like

Origin blog.csdn.net/Sheenky/article/details/124081775