【MySQL数据库】SQL语法基础--DQL(入门级)

发布于:2025-03-04 ⋅ 阅读:(16) ⋅ 点赞:(0)

在学习数据库的数据操作之前,我们应该先学习查询操作,只有学会了查询,后面操作我们才能看到操作后的反馈。


基础查询

select fieldlist from tablename;

解释:从[from]表tablename中查询,将字段列表fieldlist挑选[select]出来展示

例如:

select * from emp;

其中【*】星号 表示 表中的所有字段(empno、ename、job、mgr、hiredate、sal、comm、deptno)。如果选择特定字段显示,那么就是:

select empno,ename,sal from emp;

条件查询

直接查询

单纯的基础查询并不能解决所有问题,现在,我想找员工名叫smith的员工并获取他的信息:

语法: 

select field_list from table_name where condition_list;
等于: =
大于: >
小于: <
不等于: != ; <>
是否为空: is NULL; is not NULL

范围查询

现在我的需求是找出sal薪资大于3000的员工,展示他们的信息:

如果需求是查询薪水在1000至4000的员工信息:那么有两种写法:

select * from emp where sal >=1000 and sal <=4000;
select * from emp where sal between 1000 and 4000;

更多示例: 

select * from emp where sal between 2000 and 4000;
select * from emp where sal >= 2000 and sal <= 4000;
select * from emp where sal >= 2000 && sal <= 4000;

知识点提炼:

与: and && 
或: or ||
非: not
在范围内: between num_a and num_b  [num_a,num_b]-左右都是闭区间
(不)在列表中: (not) in

模糊查询

now!我想查询名字里包含S的员工信息:

select * from emp where ename like "%S%";

更多应用:

select * from emp where job like "s%"; #job字段中首字母为s的所有数据行
select * from emp where job like "%.cpp"; #job字段中以.cpp结尾的所有数据行
select * from emp where job like "%hello%"; #job字段中包含hello的所有数据行
select * from emp where job like "_s%"; #job字段中第二个字符为s的所有数据行

知识点提炼:

(' * ''表示字段列表中所有字段的通配写法)

(“ _ ”表示记录中数据的占位符-一个占一个)

(“ % ”表示记录中数据的通配符-一个当多个)

进阶查询1

排序查询

select * from mytb order by field[asc],field2 desc;
#查找mytb表,查询结果按照字段1升序(asc),如果字段1结果一样那就按照字段2降序(desc)排序显示
select * from mytb order by num;
#查找mytb表,查询结果按照第二列字段的数据进行升序(默认asc)排序

tips:asc 和 desc 只修饰单个字段

去重查询

select distinct job from emp;    #job不一样的结果
select distinct job,ename from emp;    #job或ename不一样的结果(同时相同才叫重)

select ename, distinct job from emp; #error,错误,无法在限制一条字段的基础上查询非限制字段
select distinct ename, distinct job from emp; #error,错误,无法“分别”限制多条字段,只能“同时”限制

select distinct * from emp;#查询记录完全不一样

组合查询

#默认去重
select id,name from student
union
select id,name from teacher

#不去重
select id,name from student
union all
select id,name from teacher

tips:组合查询时,要求列的数量相同、列的数据类型类似

进阶查询2

分页查询

select * from mytb order by field desc limit 10;
#根据字段field降序排序显示,查询结果记录数限制在前10条
select * from mytb order by field desc limit 5,5;
#从第五条数据开始往后取五条【第一个索引为0,索引为5代表第六条】

分组查询

select 字段 
from 表名 
where 条件 
group by 字段;#where 分组前过滤-不可以使用分组函数

select 字段 
from 表名 
group by 字段 having 条件;#having 分组后过滤-可以使用分组函数

执行顺序

select distinct 字段 
from 表名 
where 条件 
group by 字段 having 条件 
order by 字段 limit 数字;


#执行顺序
1.from 加载表
2.where 过滤后生成临时表
3.group by having 分组再过滤
4.select distinct 取出字段
5.order by limit 排序、限制


本章只做笔记记录目的,没有详细讲解。但是基础的语法可以用来参考。感谢大家支持! 


网站公告

今日签到

点亮在社区的每一天
去签到