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 視圖名;-- 刪除視圖
二、修改表設計
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> 保存位置。