常用的sql如增删改忽略,可自行学习(特别强调函数已加粗处理)
1.注释
--单行注释
/*
多行注释
*/
2.去重(只有所有的列全相同才会合并)
select distinct 字段 from emp;
3.字符串的连接查询
select '员工编号 ' || empno || '姓名是' || ename || '的工作是' job from emp;
4.查询的四则运算
select ename, sal*12 from emp;
5.限定查询
where
6.非空和空的限制
语法: 列名 is not null
例:select * from emp where comm is not null;
为空: 列名 is null
例:select * from emp where comm is null;
7.多条件查询
与的关系
例:select * from emp where sal > 1500 and comm is not null;
或者的关系
select * from emp where sal > 1500 or com is not null;
8.between and区间(包含边界)
语法:select * from 表名 where 字段 between 1500 and 3000;
日期区间查询:
select * from 表名 where 字段 between to_data('xxxx-xx-xx', 'yyyy-MM-dd') and
to_data('xxxx-xx-xx', 'yyyy-MM-dd')
注意:oracle所查询的值区分大小写,语句不区分大小写
9.in关键字
select * from 表名 where 列名 in (1, 2,3);
去反:
select * from 表名 where 列名 not in (1, 2,3);
10.模糊查询
“%”:可以匹配任何长度的内容
“_”:可以匹配一个长度的内容
范例:查询出第二个字为M的名字
语法:
select * from 表名 where like '_M%'
范例:查询出最后一个字符为M
select * from 表名 where like '%M'
范例:
查询出来带M字符的
select * from 表名 where like '%M%'
11.非 查询(“<>” 和“!=”)
范例:查询出雇员不叫M的
select * from 表名 where 列名 != 'M'
select * from 表名 where 列名 <> 'M'
12.结果集排序
(1)order by(ASC/DESC)默认是按照正序排列
范例:查询雇员的工资从低到高
select * from 表名 order by 列名
倒序排列
select * from 表名 order by 列名 desc
范例:如果工资相同按照入职日期升序来排
select * from 表名 order by 列名 desc, 入职日期 asc;
13.单行函数
伪表的概念:
select 1 from dual
(1)大小写转换
语法:select upper('smith') from dual
大变小
select lower('SJDF') from dual
首字母大写
select initcap('smith') from dual
(2)字符串的连接
select concat('hello', 'world') from dual;--(不跨数据库)
select 'hello' || 'world' from dual;--建议使用(跨数据)
(3)字符串的切分(索引从1开始)
select substr('原字符串',1, 3) from dual;
(4)字符串的替换
select replace('hello', 'l', 'x') from dual;
14.数值函数
(1)四舍五入
select round(12.78) from dual;
保留位数
select round(12.4646, 2) from dual;
(2)去掉小数(也可保留位数)
select trunc(12.87) from dual;
(3)取余
select mod(10, 3) from dual;
15.日期函数
select sysdate from dual;
sysdate:在oracle是当前日期
select (sysdate - 入职日期字段) / 7 from 表名;
去掉小数
select trunc((sysdate - 入职日期字段) / 7) from 表名;
(2) 获得两个月中间的月数
范例:员工入职多少月?
select months_between(sysdate, 入职日期) from 表名;
(3)加n个月函数
范例:在当前时间上加6个月
select add_months(sysdate, 6) from dual;
(4)指定给出下次某日期数next_date()
范例:求出下一个星期一是什么日期
select next_day(sysdate, '星期一' ) from dual
(5)求出一个日期的最后一天
范例: 求出本月的最后一天是几号
select last_day(sysdate) from dual;
16.转换函数
(1)to_char:字符串转换函数
select to_char(日期字段, ‘yyyy’) 年, to_char(日期,‘mm’) 月,
to_char(日期,‘ss’) 日,
to_char(日期,‘HH’) 时,
to_char(日期,‘mi’) 分,
to_char(日期,‘ss’) 秒 from 表名
(4)把字符串格式数字转换成数值类型
(5)把一个字符串转换成时间