一、DQL介绍
数据查询语言,用来查询数据库中表的记录。
查询关键字:SELETE
*语法:
SELETE
字段列表
FROM
表名列表
WHERE
条件列表
GROUP BY
分组字段列表
HAVING
分组后的条件列表
ORDER BY
排序字段列表
LIMIT
分页参数
*基本查询
*条件查询(where)
*聚合函数(count、max、min、avg、sum)
*分组查询(group by)
*排序查询(order by)
*分页查询(limit)
二、DQL语句
2.1 基本查询
2.1.1 查询多个字段
selete 字段1,字段2,字段3…… from 表名;
selete*from 表名;
2.1.2 设置别名
selete 字段1[as 别名],字段2[as 别名]……from 表名;
2.1.3 去除重复记录
selete distinct 字段列表 from 表名;
*查询主要字段
selete name,wokno,id form emp
*查询所有字段
selete id,workno,……(所有字段名) from emp;
selete*from emp;
*查询所有员工工作地址起别名
selete workaddress as '工作地址' from emp;
*查询员工上班地址(不重复)
selete distinct workaddress '工作地址' from emp;
2.2 条件查询
selete 字段列表 from 表名 where 条件列表
2.2.1 查询年龄等于88员工
selete *from emp where age = 88;
2.2.2 查询年年龄小于20员工
selete *from emp where age > 22;
2.2.3 查询没有身份证好的员工
selete *form emp where idcard is null;
2.2.4 查询有身份证号的员工
selete *from emp where idcard is not null;
2.2.5 查询年龄不等于88的员工
selete * from emp where age != 88;
2.2.6 查询性别为女且年龄小于25岁员工
selete * from emp where gender = '女' and age <25;
2.2.7 查询姓名为两个字的字符
selete * from emp where gender = '女' and age <25;
2.2.8 查询身份证任意一个字符为x的员工信息
selete * from emp where gender = '女' and age <25;
2.3 聚合函数
2.3.1 统计企业员工数量
selete count(*) from emp;
2.3.2 统计员工的平均年龄
selete avg(age) from emp;
2.3.3 统计员工的最大年龄
selete max(age) from emp;
2.3.4统计西安地区员工
selete sum(age) from emp where wordaddress = '西安';
2.4 分组查询
selete 字段列表 from 表名 [where 条件] group by 分组字段名[having 分组后的过滤条件]
where和having区别
*执行时机不同:where是分组之前进行过滤,不满足where条件不参与分组;having是对分组之后的结果进行筛选
*判断条件不同:where不能对聚合函数进行判断,但having可以
2.4.1 根据性别分组,统计男女员工数量
selete gender ,avg(age) from emp group by gender;
2.4.2 查询年龄小于45员工,并根据工作地址分组,获取员工数量大于等于3的工作地址
selete workaddress,count(*) address_count from emp where age < 45 group by worksaddress having address_count >= 3
执行顺序:where >聚合函数>having
分组之后,查询字段一般为聚合函数和分组字段,查询其它字段无意义。
2.5 排序查询
2.5.1 根据年龄对公司员工进行升序排序
selete * from emp order by asc;
2.5.2 根据入职时间,对员工进行降序排序
selete * from emp order by entrydate desc;
2.5.3 根据年龄对公司员工进行升序排序,年龄相同,再按照入职时间进行降序排序
selete * from emp order by age asc,entrydata desc;
2.6 分页查询
selete 字段列表 from 表名 limit 起始索引,查询记录数;
*起始索引从0开始,起始索引 = (查询页码-1)*每页记录数
*查询第一页数据,起始索引可省略。
2.6.1 查询第一页员工数据,每页显示10条记录
select *from emp limit 0,10;
2.6.2 查询第二页数据,每页展示10条数据
selete * from emp limit 10,10;
2.7 执行顺序