实验用到的数据:emp
1.检索所有行和列
select *
from emp
--emp 为表名称
--使用“*”查询该表所有列,或者将“*”改为需要查看的列名
2.筛选行
select *
from emp
where deptno = 10
3.查找满足多个查询条件的行
select *
from emp
where deptno = 10
or comm is not null
or sal<=2000 and deptno=20
--以上三个条件或链接:deptno = 10
--或 comm不为空
--或 sal<=2000且deptno=20
请看如下:
select *
from emp
where (deptno = 10
or comm is not null
or sal<=2000)
and deptno=20
--以上为括号里的条件的前提下,deptno=20
4.筛选列
select ename,deptno,sal
from emp
5.创建有意义的列名
select sal as salary,comm as commission
from emp
结果如下:
6.串联多列的值
select ename +'Works as A '+job as msg
from emp
where deptno=10
7.在SELECT语句里使用条件逻辑
select ename,sal,
case when sal<=2000 then 'UNDERPAID'
when sal>= 4000 then 'OVERPAID'
else 'OK'
end as status
from emp
结果如下:
8.限定返回行数
--使用TOP关键字限返回行数
select top 5 *
from emp
9.随机返回若干行记录
select top 5 ename,job
from emp
order by newid()
--order by 接受一个函数的返回值结果随机排序
拓展:
- select 字段列表/* from 表名 where 条件 order by 字段名1 asc/desc, 字段名2 asc/desc,…
- select 字段列表/* from 表名 where 条件 order by 字段序号 asc/desc, 字段序号 asc/desc,… (此时字段序号要从1开始)
- select 字段列表/* from 表名 where 条件 order by 字段别名1 asc/desc, 字段别名2 asc/desc,…(这里类似于第一种,无非就是把字段名加了个别名来代替而已。) 然后,order by的方式:
1.asc 升序,可以省略,是数据库默认的排序方式
2.desc 降序,跟升序相反。 最后要注意order by的原则,写在最前面的字段,他的优先级最高,也就是写法中第一个的字段名1的优先级最高,优先执行他的内容。
10.查找NULL值
select *
from emp
where comm is null
11.把NULL值转换为实际值
--使用coalesce函数
select coalesce(comm,0)
from emp
也可以使用CASE
select case
when comm is not null then comm
else 0
end
from emp
12.查找匹配项
select ename,job
from emp
where deptno in (10,20)
select ename,job
from emp
where deptno in (10,20)
and (ename like'%I%' or job like '%ER')