* select 查询语句基础
sql(structured query language) 结构化查询语句
投影(选择列)
选择(行)
连接(列与列连接)
NULL 值
null 值是不可用的,且未分配,未知且不适用的值
null值 和 0 或者空格是不一样的
任何包含null值的算术表达式,其结果判定为null
列的别名
重命名一个列的标题
对运算很有帮助
紧跟列后面 as
如果包含空格或特殊字符,或者大小写敏感,需要双引号
级联操作
将列或字符串和其它列串联
有两条 || 表示
结果列是一个字符表达式
消除重复行
distinct
* 查询数据的限制和排序
限制选择的行
select * |{[distinct] column | expression [alias],…}|
from table
where condition(s);
字符串和日期
字符串和日期需要使用单引号
字符值区分大小写,日期值对格式敏感
比较条件
between and in not
逻辑条件
and or not
优先级规则
1 算术操作符
2 连接操作符
3 条件比较符
4 is [not] null like [not] in
5 [not] between
6 not
7 and
8 or
使用圆括号改变优先级
order by 子句做排序
asc 升序
desc 降序
order by 在 select 语句最后面
* 典型单行函数
字符串操作函数
lower(‘SQL Course’)
upper(‘SQL Course’)
initcap() 首字母大写
cancat() 链接两个字符串
substr() 取字符串
length() 字符串长度
instr() 返回子字符串在字符串中的位置
数字处理函数
round(45.926, 2)
日期型数据函数
sysdate 系统日期
日期计算
转换函数
to_char
to_number
to_date
* 典型的分组函数(多行函数)
avg(num)
sum(num)
count(*)
max(num)
min(num)
基本格式
select group_function() from *
分组
group by
筛选
having group_condition 子句 只能接在group by 后面
分组函数可以嵌套使用
* 多表查询
表连接的三种方式
自连接、等值连接、外链接(左连接,右连接、全连接)
自连接:自己与自己的连接
等值连接:关键在于等号
外链接:两张表
* 典型子查询
定义:一个查询的输出是另外一个子查询的输入
分类:单行、多行、空值
单行:返回结果只有一列
多行:返回多行
空值:返回的值是空值
* 表结构操作语句
表:sql操作的最小对象,数据库存储数据的逻辑概念,分为行和列
创建表
create table [user].table_name
(
{column1 datatype [column_constraint]| table_constraint}
)
数据类型:varchar(L) 可变字符串
日期:date
数字:number(p,s) p 整数位 s 小数位
列约束,表约束 not null unique primary key foreign key 外键 constraint 列名 check 条件检查
创建表格
修改
增加列
alter table table_name add column_name datatype
删除列
alter table table_name drop colum_name
修改表名
alter table table_name rename to new_table_name
修改列名
alter table table_name rename column old_name to new_name
删除表格
drop table table_name cascade constraint
查看表结构
describe table_name;
* 典型的数据操作语言
DML insert update delete
insert
insert into table_name [(column [,column])] values
一次插入一行
插入新的一行,每列都包含值
插入日期 (非常特殊的类型)
to_date() 字符串到日期的转换
修改表中的行
update table_name set column_name = value where
删除行
delete from table name where
* 典型事物操作语句(确保数据库的一致性)
事物概念:数据库一系列操作的单元集合
标记事物结束
commit rollback
ddl dcl 语句 (隐式提交)
用户退出 iSQL *Plus (默认提交)
系统崩溃(隐式提交)
事物控制
commit
roll back
savepoint
roll back to
显式 commit (前、后)
之前
数据操作首先影响数据缓冲区,数据以前的状态可以改变
之后
rollback
用户直接发出撤销命令
savepoint/rollback to savepoint
使用 savepoint
* sql语句的优化 (查询优化、差距可能上百倍)为保证安全性,有时也会牺牲一些性能
避免使用 *
使用表的别名
where 子句的连接顺序, 从右向左运行
把能快速缩小查询范围的语句放在最后
使用>= 代替 >
用truncate 替代 delete
尽量多的使用commit, 释放资源
避免使用索引列上的函数