SQL 增删查改
DDL
DDL:数据定义语言
一、创建
1.创建|删除 表
--oracle常用字段类型 number() 数值类型 varchar2()可变字节型
create table 表名(
字段名 字段类型 约束,
字段名 字段类型 约束
);
drop table 表名; -- 删除表
常见约束 | 约束名 |
主键约束(唯一 + 不为空) | primary key |
唯一约束 | unique |
不能为空 | not null |
默认值 | default() |
检查约束 | check() |
2.创建|删除 索引
create index 索引名 on 表名(字段[ASC|DESC]);
--[ASC|DESC] 在列上指定排序创建索引
--不要对一个表创建3个以上的索引
drop index 索引名; --删除索引
3.创建视图
create or replace view 视图名 as select 语句 ;--对查询结果创建视图
drop view 视图名;-- 删除视图
4.创建序列
create sequence 序列名 start with 初始值 increment by 步进;
select 序列名.nextval from dual;--下一个值
select 序列名.currval from dual;--当前序列值
二、修改表设计
1.添加新字段
alter table 表名 add (字段名 类型 约束,字段名 类型 约束...);
2.修改表中字段
alter table 表名 modify(字段名 类型 约束,字段名 类型 约束...);
3.删除表中字段
alter table 表名 drop(字段名 类型 约束,字段名 类型 约束...);
4.对存在的表添加约束
alter table 表名 add constraint 约束名 约束类型(针对的字段名);
5.对表里约束 禁用 | 启用 | 删除
alter table 表名 disable constraint 约束名; --禁用
alter table 表名 enable constraint 约束名; --启用
alter table 表名 drop constraint 约束名; --删除
DML
DML:对数据操作的语言
一、插入记录
insert into 表名 (字段名1,字段名2....) values(值1,值2,...);
--如果插入所有字段值可省略表名后面的括号,插入数据顺序和表字段一一对应
insert into 表名 values(值1,值2,值3);
-- 把一个表中的数据插入另一个表中
create table a as select * from b where 1=2;--创建表且拥有b表的字段
insert into a select * from b ; --复制b表所有内容到a表
二、查询语句
distinct | 表示隐藏重复的行 |
where | 按照一定条件查询 |
group by | 分组查询(汇总时使用) |
having | 分组的条件 |
order by | 对查询结果排序 asc|desc |
1、where 语句的运算符
where 条件1 and 条件2;--俩个条件都满足
where 条件1 or 条件2;--满足一个即可
where not 条件 ; --不满足条件
where in(条件1,条件2...); --满足括号内任意条件即可
where between 条件1 and 条件2;-- 俩个条件的范围内
where 字段 like '_A&';--查询字段中第二字母是A的人
where 字段 is [not] null ; 查询字段是[不是]空的记录
2、函数
SUM --求和
AVG --平均值
MAX --最大值
MIN --最小值
count --求个数
to_char(日期,格式) 将日期转为字符串
to_char(stsdate,'yyyy');--去当前时间的 年份2019
to-date('2008-8-08 20:08:08','yyyy-mm-dd hh24:mi:ss')--将字符串转为日期
3、99查询
--内连接 inner join on
from 表1 [inner] join 表2 on 连接条件;--返回满足条件的行 inner 可省略
--自然连接 natural join
from 表1 natural join 表2;-- 返回俩张表中共同属性上做等值连接去掉重复属性
--左外连接 left join
from 表1 left join 表2 on 连接条件;--表1中不满足连接条件的行也会显示值为null
--右外连接 right join
from 表1 right join 表2 on 连接条件;--表2中不满足连接条件的行也会显示值为null
三、修改数据
update 表名 set column=new value,column2=new value..... where 条件
--将user表中id为1的name属性改为'张三'
update User set name='张三' where id=1;
四、删除数据
delete from 表名 where 条件
--将user表中id为1的数据删除
delete from User where id=1;
DCL(权限)
DCL 权限控制语句
--授权
grant 权限名称 to 用户名;
--收会授权
revoke 权限名称 from 用户名;
常见授权名称:
connect 连接
resource 资源
dba 管理员
session 会话
TCL(事物)
-- commit 提交;(确认修改)
-- rollback 回滚;(取消修改)
-- SAVEPOINT <savepoint> 保存位置。