[scode type=”share”]查询语言概念:
从数据表中提取满⾜特定条件的记录
1.单表查询
2.多表联合查询[/scode]
查询基础语法:
## select 关键字后指定要显示查询到的记录的哪些列
select colnumName1[,colnumName2,colnumName3...] from <tableName> [where conditions];
## 如果要显示查询到的记录的所有列,则可以使⽤ * 替代字段名列表 (在项⽬开发中不建议
使⽤*)
select * from stus;
where ⼦句
[scode type=”share”]在删除、修改及查询的语句后都可以添加where⼦句(条件),⽤于筛选满⾜特定的添
加的数据进⾏删除、修改和查询操作。
[/scode]
delete from tableName where conditions;
update tabeName set ... where conditions;
select .... from tableName where conditions;
条件关系运算符
## = 等于
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;
条件逻辑运算符
[scode type=”share”]在where⼦句中,可以将多个条件通过逻辑预算(and or not )进⾏连接,通过多个条件
来筛选要操作的数据。
[/scode]
## 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;
LIKE ⼦句
[scode type=”share”]在where⼦句的条件中,我们可以使⽤like关键字来实现模糊查询[/scode]
select * from tableName where columnName like 'reg';
[scode type=”yellow”]在like关键字后的reg表达式中
% 表示任意多个字符(%o% 包含字⺟o)
_ 表示任意⼀个字符(_o% 第⼆个字⺟为o)[/scode]
排序 – order by
[scode type=”share”]将查询到的满⾜条件的记录按照指定的列的值升序[/scode]
select * from tableName where conditions order by columnName asc|desc;
[scode type=”yellow”]order by columnName 表示将查询结果按照指定的列排序
asc 按照指定的列升序(默认)
desc 按照指定的列降序[/scode]
聚合函数
[scode type=”share”]SQL中提供了⼀些可以对查询的记录的列进⾏计算的函数
[/scode]
count 统计个数
max 求最大值
min 求最小值
sum 求总和
avg 求平均值
分组查询 – group by
[scode type=”share”]就是将数据表中的记录按照指定的类进⾏分组[/scode]
select 分组字段/聚合函数
from 表名 [where 条件] group by 分组列名 [having 条件] [order by 排序字段]
[scode type=”blue”]select 后使⽤ * 显示对查询的结果进⾏分组之后,显示每组的第⼀条记录(这种显示通常是⽆意义的)
select 后通常显示分组字段和聚合函数(对分组后的数据进⾏统计、求和、平均值等)
语句执⾏属性:
先根据where条件从数据库查询记录
group by对查询记录进⾏分组
执⾏having对分组后的数据进⾏筛选[/scode]
分⻚查询 – limit
[scode type=”share”]当数据表中的记录⽐较多的时候,如果⼀次性全部查询出来显示给⽤户,⽤户的可读性体验性就不太好,因此我们可以将这些数据分⻚进⾏展示。
[/scode]
select ...from ... where ... limit param1,param2
[scode type=”green”]param1 int 表示获取查询语句的结果中的第⼀条数据的索引(索引从0开始)
param2 int, 表示获取的查询记录的条数(如果剩下的数据条数<param2,则返回剩下的所有记录)
[/scode]