sql 教程系列 一、检索数据

在开始本教程之前,需要准备两张表 ,这个在oracle中是有的 大家都知道的emp 和dept表

emp (empno,ename,job,mgr,hirdate,sal,comm,depetno)
dept(deptno,dname,loc)

sql语句大部分适合myql

1从表中检索数据

select * from emp (*代表所有的列都要返回)

2从表检索出部分列

select empno,ename from emp(指定列的名字,逗号相隔就可以了)

3查找满足条件的列

select  * from emp where empmo= 12300(可以在where后面加限制的条件)
select * from emp where empno = 67777 and depto=10 (满足多个条件用and联接就可以了 是且的意思)
select * from emp where empno =898989 or deptno = 11(满足员工号为898989 或者部门为10的员工的结果)

3为列取别名

select sal as salary ,comm as commission  from emp ( as 加别名 as 可以省略)

4在where中使用别名

select sal as salary from emp where salary >10000 是错的

sql执行的顺序是先进行from 然后进行where进行过滤 ,最后执行select 所以在执行where 的时候还没有执行select 也就不知道别名到底是哪列了

解决的方法有就是使用内联视图

select * from (
       select sal as salary from emp  
) x
 where x.salary>10000

可见这样的效率极低啊  

5在select中使用逻辑条件语句

有这么一个需求 ,查询一个员工表 ,如果工资大于1000就显示high,小于500就显示lower,如果在两者之间就显示ok

select ename , sal,
  case when sal<500 then 'lower'##case when then就是相当于java中的if else
          when sal >1000 then 'high'
          else 'ok'
  end as status#给列取别名 
from emp
6分页

select * from emp limit 0,5#返回前五条
select *from emp limit 2,5#从第二条开始获取他后面的五条记录
7对空值的限制

select  * from emp where com =null #错误
select * from emp where comm is null#正确 取反的用 is not null
8查询到空值的时候将其转换为实际想要的值

例如你在查询奖金的时候要是查询到null,你想到得到是0,那么怎么办呢?

select coalesce(comm,0) from emp #意思是说如果comm为null 就返回0 不为null 就返回其本身

还可以用逻辑判断

select case
                when comm is null then 0
                else comm
             end as commission
from emp

9 in语句

如果你要查询部门为10 和20的员工信息

select * from emp where deptno in(10,20) # 取反 就是not in
这样语句在数据最后会转换为
select * from emp were deptno = 10 or dept= 20
如果数据量很大,这种查询效率很低的,应该exits 和not exits
10模糊查询

查询员工名字已M开头的信息

select * from emp where ename like 'M%'

sql中还提供了下划线 _ 来匹配单个字符 ,这里就不举例子了





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飓风zj

感谢打赏,thanks

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值