3.MySQL数据库-简单查询

四、SQL-查询

1.简单查询

1.1查询单个字段
语法:select 查询列表 from 表名;

#例子:查询单个字段-查询员工姓名
select ename from emp;
1.2查询多个字段
#例子:查询多个字段-查询员工姓名和工资
select ename,sal from emp;
1.3查询所有字段
select * from emp;
1.4查询字段重命名-查询员工姓名以中文显示字段
#(1)使用as字段
select ename as '姓名' from emp;
#(2)使用空格
select ename '姓名' from emp;
1.5查询不重复的记录-查询员工涉及到的部门编号有哪些?
select distinct depno from employees;

2.条件查询

运算符 说明
= 等于
<>或!= 不等于
between … and …. 两个值之间,等同于 >= and <=
is null 为null(is not null 不为空)
and 并且
or 或者
in 包含,相当于多个or(not in不在这个范围中)
not not可以取非,主要用在is 或in中
like like称为模糊查询,支持%或下划线匹配%匹配任意个字符下划线,一个下划线只匹配一个字符
2.1查询工资等于5000的员工姓名
select ename from emp where sal = 5000;
2.2查询薪水不等于5000的员工
select ename,sal from emp where sal <> 5000;
select ename,sal from emp where sal != 5000;
2.3查询薪水为1600到3000的员工
#between … and …
select empno, ename, sal from emp where sal between 1600 and 3000;
#>=和<=
select empno, ename, sal from emp where sal >= 1600 and sal <= 3000;
2.4查询哪些人津贴为NULL
select ename,sal,comm from emp where comm is null;
2.5查询哪些人津贴不为NULL
select ename,sal,comm from emp where comm is not null;
2.6查询哪些人没有津贴
select ename,sal,comm from emp where comm is null or comm = 0;
2.7查询工作岗位为MANAGER ,薪水大于2500的员工
select * from emp where job='MANAGER' and sal > 2500;
2.8查询出job为manager 或者 job为salesman的员工
#or操作符
select * from emp where job='MANAGER' or job='SALESMAN';

#in操作符
select * from emp where job in ('manager','salesman');
2.9查询出薪水包含1600和薪水包含3000的员工
select * from emp where sal in(1600, 3000);
2.10查询出薪水不包含1600和薪水不包含3000的员工
#<>、and操作符
select * from emp where sal <> 1600 and sal <> 3000;

#not、or操作符
select * from emp where not (sal = 1600 or sal = 3000);

#not、in操作符
select * from emp where sal not in (1600, 3000);
2.11查询出津贴不为null的所有员工
select * from emp where comm is not null;
2.12条件查询-like
#查询姓名以M开头所有的员工
select ename from emp where ename like 'M%';

#查询姓名以N结尾的所有员工
select ename from emp where ename like '%M';

#查询姓名中包含O的所有员工
select ename from emp where ename like '%O%';

#查询姓名中第二个字符为A的所有员工
select ename from emp where ename like '_A%'

3.排序

3.1单一字段排序
#按照薪水从小到大排序
select * from emp order by sal;

#取得工作岗位为MANAGER的员工,按照薪水由小到大排序
select * from emp where job='MANAGER' order by sal;
3.2手动指定排序顺序
#手动指定按照薪水由小到大排序
select * from emp order by sal asc;

#手动指定按照薪水由大到小排序
select * from emp order by sal desc;
3.3多个字段排序
#按照工作岗位和薪水倒序
select * from emp order by job desc, sal desc;
3.4按别名排序
#查询每个员工一年的薪水,并显示字段名字为nianxin,按nianxin降序排序
select ename,sal,sal*12 nianxin from emp order by nainxin desc;
发布了11 篇原创文章 · 获赞 1 · 访问量 3238

猜你喜欢

转载自blog.csdn.net/qq_42250189/article/details/104793321