学习oracle已经有一段时间了,为了复习前面学过的内容,打算逐步将相 关的知识点整理到优快云博客上,以加深印象。从大的方面划分,sql语句主要分为五类:select查询语句;DML数据操作语句;DDL数据定义语句;TCL事物控制语句;DCL数据控制语句。后面将一一梳理。
首先假设有一个表:s_emp,表结构如下:
id(number) name(varchar2(30)) salary(number)
1 tom 7800
2 jerry 8800
3 mike NULL
一 Select查询语句
1、from子句
(1)查询一个字段:
select 字段名 from 表名;如:select id from s_emp;
(2)查询多个字段,每个字段间用逗号隔开:
select 字段1名, 字段2名 from 表名;如:select id,name from s_emp;
(3)查询所有字段,一般有两种方法,一种是穷举所有字段名,另一种是用“*”代替所有字段:
select * from s_emp;如:select * from s_emp;
两种方法各有优劣,第一种方法很直观,可以很好的展现表的数据结构,但是书写很繁琐;
第二种方法,书写简单,但是无法表达表的结构。
(4)字段中的数学运算
select 字段名 数学运算符(+、-、*、/)from 表名如:算年薪 select salary*12 from s_emp;
(5)字段或者表达式的别名
select 字段名 别名 from 表名如:还是算年薪 但是给字段另取一个别名 year_salary
select salary*12 year_salary from s_emp;
值得注意的是这里的year_salary在sqlplus中显示时默认显示的是大写的,也就是显示成YEAR_SALARY,而且别名只能用一个单词,中间不能有空格,即不能写成year salary 。要同时解决上述两个问题,就需要在别名上扩上双引号,即:
select salary*12 "year salary" from s_emp;
(6)字符串
a、用单引号来表示字符串如,在sqlplus中显示hello world:select 'hello world' from s_emp;
b、两个字符串用“||”进行拼接
还是在sqlplus中显示hello world:select ‘hello’|| ‘world' from s_emp;
特殊用法,如果需要显示hello'world怎么办?(注意hello'world中间有单引号)
select 'hello'||''''||'world' from s_emp;
与C语言中输出%的方法类似,sql语句中输出一个单引号时,需要用用两个单引号
(7)NULL值的处理
NULL 值和任何值做运算的结果都是NULL如,想查看mike的年薪,但是表中其月薪是NULL
select salary*12 "year salary" from s_emp where name='mike';
发现最后的结果year salary 也是NULL;
可以用函数nvl(参数1,参数2)来处理NULL值,该函数的的含义是,若参数1不为NULL则返回参数1的值,参数1为NULL,返回参数2的值
如,如果mike的月薪为NULL,则用5000来计算年薪
select nvl(salary,5000)*12 "year salary" from s_emp;
(8)数据的去重显示
当表中存在重复的数据时,用distinct关键字来排重select distinct id from s_emp;
2、 where子句
where条件子句,符合where条件的就被选中,不符合where条件的被排除(1)数字类型的条件
where id=1;(2)字符串类型的条件
where name='mike';(3)where后可以使用=,>=,<=,!=,>,<等比较运算符
where salary>=5000;(4)sql语句中的运算符
a、表达一个闭区间如id从1到3:where id between 1 to 3;
b、在一个列表中
如id为1或者3:where id in (1,3);
c、模糊查询
一般形式:where 字段 like 通配串;
通配串的构造形式如下:
%表示任意长度的字符串,如一个姓李的人 where name like '李%';
_表示一个任意字符,如一个倒数第二个字是龙的人 where name like '%龙_';
\表示转意字符,如以名字以S_开头的人 where name like 'S\_%' escape '\';
(5)用is判断NULL的值
where name is NULL;where name is not NULL;
(6)SQL提供的逻辑运算符
与 and: where salary>1000 and salary<100000;或 or: where id=1 or id =2;
非 not:
between 的对立面not between:where id not between 1 to 3;
in的对立面 not in:where id not in (1,3);
like的对立面not like: where name not like 's\_%' escape '\';
is NULL的对立面is not NULL: where name is not NULL;
3、 order by子句排序
(1)order by子句一定在sql语句的最后
升序(默认的排序方式):order by 字段名 asc;降序: order by 字段名 desc;