6 select语句
6.2 where子句(条件子句)
1、where的作用,是对表中行数据进行限制,符合where条件数据就被选中,不符合where条件数据就被过滤掉。
select id,salary from s_emp;
select id,salary from s_emp where 1=1;
select id,salary from s_emp where 1=2;
2、number类型数据判断
查询工资大于1400的员工的id和first_name,salary
select id,first_name,salary from s_emp where salary>1400;
查询工资小于1400的员工的id和first_name,salary from s_emp where salary<1400;
查询工资等于1400的员工的id
select id,salary from s_emp where salary=1400;
3、字符串类型的数字
查询first_name叫carmen的员工的id,first_name,salary from s_emp where first_name=’Carmen’;
/*在sql中,字符串的值是要严格区分大小写的*/
4、where条件后的运算符号
> < = >= <= !=
5、sql提供了一些可以用在where后的运算符
a、where 字段 between a and b
表达一个闭区间[a,b]
列出工资在[1000,2000]之间的员工的id,salary
select id,salary from s_emp where salary between 1000 and 2000;
/*数字写反了,就查不到,逻辑错误*/
b、where 字段 in (值的列表)
列出部门编号是41或者是50的部门的员工的id,dept_id
select id,dept_id from s_emp where dept_id in (41,50);
出现概率高的数据放前面,可提高查询效率。
c、模糊查询
where 字段 like ‘通配串’
sql中的通配符:
% — 0-n个任意字符
_ — 1个任意字符
where 字段 like ‘王%’;
where 字段 like ‘%涛%’;
列出s_emp中first_name所有带a的
select first_name from s_emp where first_name like ‘%a%’;
列出s_emp表first_name所有第二个字符是a的
select first_name from s_emp where first_name like ‘_a%’;
desc user_tables;
select table_name from user_tables;
查询user_tables中所有的S_开头的表
select table_name from user_tables where table_name like ‘S_%’;
/*需要进行转义*/
select table_name from user_tables where table_name like ‘S\_%’ escape ‘\’;
select table_name from user_tables where table_name like ‘S\_\_%’ escape ‘\’;(两个下划线开头的)
/*建立S__开头的表*/
create table s__testgg(id number);
d、where 字段 is null;
判断一个字段的值是不是NULL
找出manager_id是NULL的员工的id first_name manager_id
select id,manager_id from s_emp where manager_id is null;
查询提成是10的员工的id first_name salary
select id,salary from s_emp where commission_pct=10;
查询提成不是10的员工的id first_name salary
select id,salary from s_emp where commission_pct!=10;
查询提成是NULL的员工的id first_name salary(提成为空的既不在等于10里面也不在不等于10里面)
select id,salary from s_emp where commission_pct is null;
6、逻辑运算符
and
实现工资在[1000,2000]之间的员工的id first_name salary
select id,salary from s_emp where salary>=1000 and salary<=2000;
实现工资(1000,2000)之间的员工的
select id,salary from s_emp where salary>1000 and salary<2000;
or
求部门编号是41或者是50的部门的员工的id first_name dept_id
select id,dept_id from s_emp where dept_id=41 or dept_id=50;
not
> <=
< >=
= != <> ^=
between a and b — not between a and b
in — not in(注意NULL的值)
like — not like
is null — is not null
/*提成不是NULL员工的id first_name commission_pct*/
select id,salary from s_emp where commission_pct is not null;
6.3 数据排序
order by 排序标准 排序方式;
order by 出现在sql语句最后
排序标准:排序的字段
排序的方式:升序 — 默认的排序 asc 自然顺序 字典顺序
降序 – desc 反自然顺序 反字典顺序
按照工资排序,列出id first_name salary
select id,salary from s_emp order by salary;
按照工资降序排列
select id,salary from s_emp order by salary desc;
按照manager_id排序,列出id first_name manager_id
select id,manager_id from s_emp order by manager_id desc;
/*空值(NULL)在排序中当作最大值来处理*/
/*当按着某个字段排序时,如果值相同了,我们可以启用第二排序字段*/
select id,salary from s_emp order by salary desc,id desc;
order by 排序标准 排序方式,排序标准2 排序方式;