查询语句的子句执行顺序

 1.词法分析与优化,读取SQL语句

 2.from,选择数据来源

 3.where,筛选出符合条件的记录

 4.group by, 对where筛选出的记录分组

 5.select,选择输出内容

 6.order by,对结果排序

 7.limit,规定结果集中出现的数量

简单查询:

#记录查询,最基本的查询语句是由 select 和 from 关键字组成的
select * from t_emp;
select empno,ename,sal from t_emp;
#使用列别名查询
select
 empno,
 sal*12 as "income"
from t_emp;

数据分页:

#从第0条开始,往后取5条数据
select empno,ename from t_emp limit 0,5;

#从第5条开始,往后取5条数据
select empno,ename from t_emp limit 5,5;

#数据分页的简写
#如果limit子句只有一个参数,它表示的是偏移量,起始值默认为0
select empno,ename from t_emp limit 10;
select empno,ename from t_emp limit 0,10;

结果集排序:

  如果排序列是数字,则按数字大小排序,如果排序列是日期,则按日期大小排序,如果排序列是字符串,就按字符串的字典序排序。默认情况下,如果两条数据排序字段内容相同,则按主键大小排序。

#asc升序(默认),desc降序
select empno,ename,sal,deptno from t_emp order by sal
select empno,ename,sal,deptno from t_emp order by sal asc;
select empno,ename,sal,deptno from t_emp order by sal desc;

  我们也可以使用order by规定首要排序条件和次要排序条件。数据库会先按照首要排序条件排序,如果遇到首要排序内容相同的记录,那么就会启用次要排序条件接着排序 

select
empno,ename,sal
from t_emp
order by sal desc,hiredate asc;
limit 5;

去除重复记录 

  使用distinct去除结果集中的重复记录,不会改变数据表的数据,使用distinct的select句中只能查询一列数据,如果查询多列,去除重复记录就会失效。

select distinct job from t_emp;

条件查询

  很多时候用户感兴趣的并不是逻辑表里的全部记录,而只是它们当中能够满足某一种或某几种条件的记录。这类条件要用where子句来实现数据的筛选。

  where子句中,条件执行的顺序是从左到右。我们应该把索引条件放在最左侧,其次是筛选记录最多的条件,最后是普通条件,这样会使查询速度最快

  where语句中的条件运算会用到四种运算符:

  数学运算符:+   -   *   /   %

  比较运算符:>   <   =   !   !=   in(包含)   is null(为空)   is not null(不为空)   between...and...(范围)   like(模糊查询)   regexp(正则表达式)

  逻辑运算符:and(与)   or(或)   not(非)   xor(异或)   

  按位运算符:&(位与)   |(位或)   ~(位取反)   ^(位异或)   <<(左移)   >>(右移)   

 null与数学运算符进行运算,结果都是null

 异或:age>18 xor sex="男"  左边右边都是false,才返回false,否则都是true

#查询10,20部门里工资大于2000的员工
select empno,ename,sal
from t_emp
where (deptno=10 or deptno=20) and sal>=2000;

#查询10部门里年收入超过15000,且工龄大于20年
#ifnull(comm,0)如果comm字段为null则返回数字0
#datediff(now(),hiredate)返回两个日期相差多少天,now()获取当前时间
select empno,ename,sal,hiredate
from t_emp
where deptno=10 and (sal+ifnull(comm,0))*12>=15000
and datediff(now(),hiredate)/365>=20;

#查询10,20,30部门里在1985年以前入职,且不能是SALESMAN职位的员工
select 
   empno,ename,sal,deptno,hiredate
from t_emp
where deptno in(10,20,30) and job!="SALESMAN"
and hiredate<"1985-01-01";

#查找佣金为空,工资在2000-3000之间,名字含字母A的员工
select ename,comm,sal from t_emp 
where comm is null
and sal between 2000 and 3000
and ename like "%A%";

#查询部门不是10,20 和 工资大于2000的员工(结果包含10,20部门的员工)
select
  ename,deptno,sal
from t_emp
where not deptno in(10,20) xor sal>=2000;