文章目录
1基本查询
1.1语法格式
1.2案例
- 查询所有员工记录
- select * from employee;
- 查询员工号 姓名 月薪
- select id, name,salary from employee;
- 使用别名查询员工号 姓名 月薪
- select id as 员工号, name 姓名,salary 月薪,salary*12 年薪 from employee;
- 在使用别名中
- as 可以省略
- 如果别名中有空格需要使用" "引起来。
1.3特殊函数和关键字
1.3.1nvl()函数
- select id as 员工号, name 姓名,nvl(salary,0) 月薪,salary*12 年薪 from employee;
- 因为包含NULL的表达式都会为空 ,导致整个查询语句都为空,所以查询的行有一个列为空都无法查到整个行
- 解决方法:nvl(a,b) 若a为NULL 则去b值
1.3.2distinct
SELECT distinct sname,salary from class;
- 作用:去重
- 范围:关键字后面的列
1.4 注意点
1.4.1查询系统当前日期
- select sysdate from dual;
- dual 是个伪表 主要是为了满足sql语法的规定
1.4.2C
- 在编写sql语句是,出现语法错误 则可以用C
1.4.3保存查询结果
-- 地址加文件名
spool D:\result;
select * from emp;
spool off;
2where条件
2.1where后面使用比较运算符
> < = != (< >) between and
- 查询员工的名字为员工信息
select * from employee where name='庄三';
结论:表中的数据区分大小写 但是关键字和列名不区分大小写
- 查找薪水不等于1500的员工信息
select * from employee where salary!=1500;
select * from employee where salary<>1200;
- NULL会让整个表达式为假
select * from employee where nvl(salary,0)<>1500;
- 查询入职日期为2015-06-12的员工信息
select * from employee where entry_date='2015-06-12';
- 注意两者的时间格式一定要相等
- 查询工资介于1000-2000的员工信息
select * from employee where salary>=1000 and salary<=2000;
select * from employee where salary BETWEEN 1000 and 2000;
结论 between是闭区间包含它的边界值
2.2逻辑运算符
or and not
- 查询id为1 或 2 的员工信息
select * from employee where id=1 or id=2;
- 查询id为1 或 salary=1500 的员工信息
select * from employee where id=1 or salary=1500;
- 关于and or的优化问题
- and时:把最容易出现假的表达式放在右边,因为一个为假 mysql 就不会去判断后面的表达式
- or时 最容易为出现真的表达式放在右边,因为一个为真 mysql 就不会去判断后面的表达式
- 在where条件中 and的优先级比or高 所以若where条件中有or和and时 使用or应该拿括号括住
查询salary为NULL 的员工信息
select * from employee where salary is NULL;
select * from employee where salary is not NULL;
判断一个值是否为NULL时 不用等于号 用 is / is not
2.3集合in / not in
- 查询员工是1或者2的员工信息
select * from employee where id in (1,2);
select * from employee where id not in (1,2);
- 结论
- 可以再in 中使用NULL 因为id in(1,2)相当于id=1 or id=2;
- 不可以再not in 中使用NULL 因为id not in(1,2)相当于id!=1 and id!=2;
2.3模糊查询like(%匹配多个字符,_匹配一个字符)
- 查询员工姓名字母是"庄"的员工信息
select * from employee where name like '庄%'
- 查询员工姓名字母2个字的长度的员工信息
select * from employee where name like '__'
注意如果要查询名字里面有 ‘_’ 字符的人 要使用转义字符
select * from employee where name like '%\_%' escape '\';
escape设置转义字符
- 注意: 在模糊查询中如:’%d% '只有后面的%才会通过索引来查询
3排序函数
select 列名 from 表名 where 表达式 order by ---
- 排序有两种排序 默认升序asc 降序 desc
3.1使用列名进行排序
- 使用id进行排序
select * from employee ORDER BY id;
select * from employee ORDER BY id desc;
- 使用薪水进行排序
select * from employee ORDER BY salary ;
select * from employee ORDER BY salary NULL last;
NULL的值表现为无穷大
- id 进行升序排序 salary 进行降序排序
select * from employee ORDER BY id,salary desc;
在进行多列排序时 先按照第一列进行排序 ,然后在第一例相同的区间在进行第2列排序依次内推
3.2使用序号进行排序 序号:select后面列名的顺序
select id,name,sex, salary from employee ORDER BY 4;
3.3使用别名进行排序
select id,name,sex, salary,salary*12 '年输入' from employee ORDER BY '年输入';
3.4使用表达式进行排序
select id,name,sex, salary,salary*12 from employee ORDER BY salary*12;