SQL查询_基本查询
select 用于指定查询所获得的结果列,from 指定查询的数据源,数据源可以是一个表,也可以是一个临时记录集合,若from后面有多个数据源,这些数据源经实现笛卡尔积,即第一个数据源的每条记录与第二个数据源中的所有记录组合,最终形成新的数据源
如:select * from employee,hh;
where用来过滤数据源,distinct 获得唯一性记录,可以是单个列,也可以是多列组合
一、查询语法
select [distinct] 字段名1,……|* from 表名 where[查询条件];
1.1、查询表中所有字段
select * from 表名;
1.2、查询表中指定字段
select 字段1,字段2,…… from 表名;
1.3、给字段设置别名
select 字段名 as 新字段名 from 表名;(as可以省略)
二、运算符
算数运算符(+,-,*,/)
比较运算符(>,>=,<,<=,<>)
逻辑运算符(and,or,not)
select * from employee where emp_salary is not null;
select * from employee where not(emp_salary=5000);
备注:not加在表达式前三、模糊查询(like)
通配符:下划线(_)、百分号(%)
_:代替一个字符select * from employee where emp_name like '张_';
%:代替0到多个字符select * from employee where emp_name like '张%';
四、范围查询
4.1、between……and(主要针对数值)
select * from employee where emp_salary between 1000 and 6000;(包含1000和6000)
备注:between……and 包含起始数据4.2、in(主要针对对象)
select * from employee where emp_name in('张三','李四');
五、对查询结果进行排序(order by)
语法:select……from 表名 [where……] order by 字段1 desc/asc,字段2 desc/asc,…… (desc:降序,asc:升序)
select * from employee order by emp_name desc;
select * from employee order by emp_name desc,emp_salary asc;
备注:可以按多个字段进行排序,字段1相等的情况下再字段2排序六、对记录集合进行分组(group by)
一旦使用了分组,select 语句的真实 操作目标为各个分组数据,每次循环处理的也是各个分组,而不是单条记录
语句:select distinct emp_department,avg(emp_salary) from employee group by emp_department;
EMP_DEPARTMENT AVG(EMP_SALARY)
-------------------- ----------------------
项目部 5500
工程部 4550设计部 5000
七、having子句
having子句是针对group by 子句形成的分组之后的结果集的过滤
语句:
select distinct emp_department,avg(emp_salary) from employee group by emp_department having avg(emp_salary)>=5000 order by avg(emp_salary);
结果:
EMP_DEPARTMENT AVG(EMP_SALARY)
-------------------- ----------------------
设计部 5000项目部 5500
网友评论