基础编
检索记录
-
检索所有的行和列
select * from table
方便简易,但是建议输入具体列,方便后人维护代码 -
筛选行
使用where 过滤需要的行
如select * from emp where deptno = 10 得到编号为10的所有员工 -
List item
-
查询满足多个查询条件的行
使用 and 或者or 来满足查询
比如select * from emp where deptno= 10 or comm is not null or sal <= 2000 and deptno =20
的查询 编号为10 的员工 、有提成的员工、工资低于2000 且编号为20 的员工的并集 -
筛选列
select ename, deptno, sal from emp (字面意思) -
创建有意义的列名(其实就是给列起别名)
select sal as salary, comm as comission from emp -
在where 字句中引用别名列
如 select sal as salary, comm as commission from emp where salary > 1000
会报错的,原因是 where 先于 select 语句先行,所以 还没有 别名的时候 你使用了,结果会看见没有这个列的提示,如果非要要别名过滤,首先有个笨蛋点的方法 如 select * from select sal as salary, comm as commission from emp ) x where salary > 1000 后续有空介绍些 高级点的 比如 聚合函数 -
串联 多列的值
如果你想将 字段a 和字段b 合在一起
select concat(a,b) from table
如果你想将 字段a和字段b 在中间加上其他字符如 a 喜欢 b
select concat(a,‘喜欢’,b) from table
concat 函数的参数个数没有限制(反正我没用到超过限制的) -
在select 语句里使用条件逻辑
select ename, sal, case
when sal <= 2000 then ‘UNDERPAID’
when sal >= 4000 then ‘OVERPAID’
else ‘OK’
end as status
from emp
字母意思 -
限定返回行数
select * from emp limit 5
在限定行数中 oracle 有个坑 比如 oracle 的语法是 select * from emp where rownum <=5,原理是当oracle 执行查询的时候取得行号为1,所以 当你 用条件 rownum = 5 想取第五行的时候,你会发现一辈子都无法完成,细节自己想想 -
随机返回 若干条记录
select emp, job from emp order by rand() limit 5 -
查找 null 值
有 也只有一种方法 select * from emp where comm is null -
把null 转成实际值
select coalesce(comm,0) from emp 将comm字段的null 值返回0,当然,你也可以用 case 语法去写 -
查找匹配项
select ename, job, from emp where depno in(10,20) and (ename liek ‘%I%’ or job like ‘%ER%’)
%er 表示左边模糊匹配 er结尾 ,%er%表示 er左边模糊匹配 er 的右边也是模糊匹配
单个字符匹配用_ ,如e_r表示e和r之间随意匹配字符