**
sql基礎知識(筆記)(三)
個人學習筆記
**
接上篇
sql基礎知識(筆記)(一)
sql基礎知識(筆記)(二)
**
DDL部分:
**
建表:
**
create table 表名
(
列名 資料型別(長度),
列名 資料型別(長度),
列名 資料型別(長度)
);
comment on table 表名 is '注釋內容';
comment on column 表名.列名 is '注釋內容';
1.表名的選取:盡量體現表的功能,單詞縮寫和下劃線組成
2.列名的命名:體現列資料內容,單詞縮寫和下劃線組成
3.表和列都需要有注釋;
4.默認值和非空校驗:
create table 表名
(
列名 資料型別(長度) default 0,
列名 資料型別(長度) defualt sys_guid(),--32位
列名 資料型別(長度) not null
);
新增列:
alter table 表名 add 列名 資料型別(長度);--加一列
alter table 表名 add (列名 資料型別(長度), 列名 資料型別(長度),列名 資料型別(長度));
洗掉列:
alter table 表名 drop column 列名;--洗掉一列
alter table 表名 drop(列名1,列名2,列名3);--洗掉多列
修改列:
alter table 表名 modify 列名 新的資料型別(新的長度);
1.修改列型別時,列必須為空;
2.列擴長是可以的,但數字型別無法縮小,字串型別縮小到現有資料最大長度;
表重命名:
alter table 表名 rename to 新表名;
列重命名:
alter table 表名 rename column 列名 to 新列名;
**
視圖
**
基本語法:
create or replace view as select 陳述句;
select可以是基本的篩選查詢,也可以是使用了group by,having的陳述句
1.視圖的基本作用:屏蔽資料;
2.不是所有的視圖都能更新;
3.視圖不起到任何提高查詢效率的作用;
**
臨時表
**
基本語法:
create global temporary table
(
列名 資料型別(長度),
列名 資料型別(長度),
列名 資料型別(長度)
) on commit delete rows;--提交洗掉資料 事務級別
create global temporary table
(
列名 資料型別(長度),
列名 資料型別(長度),
列名 資料型別(長度)
) on preserve delete rows;--關閉視窗洗掉資料 session級別
另有 on commit preserve rows,類似 on preserve delete rows,會話結束洗掉資料
1.臨時表占用臨時表空間;
create user 用戶名 identified by 密碼 default tablespace 固定表空間 temporary tablespace 臨時表空間;
索引
索引概念:起加快查詢的作用,跟字典的索引頁相同
普通索引
create index 索引名字 on 表名(列名);
1.索引名字以IND或者IDX開頭;
2.單列索引,每個列只有一個單列索引;
3.索引名字長度有限制 30位;
4.索引列選取唯一性高的(資料重復少的);
5.每個表的索引盡量控制在5個以內;
唯一索引:
create unique index 索引名 on 表名(列名);--要求索引列里的資料唯一(不重復),但可以為空;
組合索引
create index 索引名 on 表名(列1,列2);
1.列1的順序決定where條件中條件寫的順序;
2.唯一性高的列放在前面;
3.組合索引使用時,須要用到第一個索引列;
約束
非空:
1.alter table 表名 modify 列名 not null;
2.alter table 表名 modify 列名 null;–修改列的值可為空,不是講列的值改為空(update)
3.建表時列名 資料型別(長度)后跟not nul;
唯一:值不能重復,但可以為空;會自動建一個同名唯一索引
1.alter table 表名 add constraint 約束名字 unique(列名);
2.建表最后,單獨一行 constraint 約束名字 unique(列名);
3.建表時,在 列名 資料型別(長度)之后加 constraint 約束名 unique;
檢查:
1.alter table 表名 add constraint 約束名 check(檢查內容);
2.建表最后,單獨一行 constraint 約束名 check(檢查內容);
3.建表時,在 列名 資料型別(長度)之后加 constraint 約束名 check(檢查內容);
主鍵:區別于唯一約束,索引列不能為空,切值不能重復;
語法:
1. alter table 表名 add constraint 約束名 primary key(列名);--索引列不會用來查詢
2. create unique index 索引名 on 表名(列名);--索引列是有業務含義的,會經常拿來查詢
alter table 表名 add constraint 索引名 primary key(列名) using index 索引名;
注意:
1.每個表只能有一個主鍵;
2.主鍵以PK開頭;
3.merge里的on后應該是主鍵;
外鍵
插入資料時,先插入主表,再插入子表;
洗掉資料時,先洗掉子表,再洗掉父表;
基本語法:
1.alter table 表名 add constraint 約束名 foreign key(列名) references 主表(主表列);
2.alter table 表名 add constraint 約束名 foreign key(列名) references 主表(主表列) on delete cascade;--級聯洗掉,洗掉父表資料時,同時洗掉子表資料
3.alter table 表名 add constraint 約束名 foreign key(列名) references 主表(主表列) on delete set null;--級聯置空, 洗掉父表資料時,子表外鍵列對應的行資料置空
注意:
1.外鍵以FK開頭;
2.依賴的主表的主表列,必須是主鍵或者有唯一約束;
3.因為外鍵使用偏復雜,所以現在較少使用;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/242442.html
標籤:其他
上一篇:location物件的屬性與方法
下一篇:第 0 章 Readme
