資料庫 (四) -- 資料定義
阿新 • • 發佈:2021-07-12
約束
防止合法使用者向資料庫加入不符合語義的資料,避免非法更新
- 主鍵約束 Primary Key
增加一個主鍵將自動在主鍵中列出的列或列組上建立一個唯一 B-tree 索引
CREATE TABLE products { product_no integer Primary Key -- 或者 product_no integer, product_secno integer, Primary Key (product_no, product_secno) }
- 外來鍵約束 Foreign Key
CREATE TABLE orders (
order_id integer PRIMARY KEY,
product_no integer REFERENCES products (product_no),
quantity integer
);
- 屬性約束 全域性約束
- not null
- unique
- check 可以是任何 WHERE 子句
- GRANT REVOKE
授權 和 收回許可權
靜態約束
Integrity Constraint ::= (O, P, A, R)
CREATE TABLE Course ( C char(3), Credit float(1) constraint ctcredit check (Credit >= 0.0 AND Credit <= 5.0) -- 指定約束名為 ctcredit )
動態約束
** 觸發器 Trigger
實現動態完整性,在特定時刻自動觸發
CREATE TRIGGER updS# after undate of S#
ON student
referencing old oldi, new newi
for each row
begin
update sc set S# = newi.S# where S# = :oldi.S#;
end;
檢視 View
- 基本表儲存到檔案中
- 虛擬表,對真實表的引用
- 使用表的一部分而不是整個表,也有利於保護資料
- 隱藏複雜 SQL
CREATE VIEW vend_usa AS SELECT vend_id, vend_address, vend_country FROM vendors WHERE vend_country = 'USA' WITH CHECK OPTION ; -- 這裡新增載 WITH CHECK OPTION,之後對檢視的增刪改自動添加當前的 WHERE 條件
檢視更新: 檢視由一個單一表子集構成,並且更新操作包含基本表的主鍵,可以更新
儲存過程 (函式)
WITH
WITH 提供了一種方式來書寫在一個大型查詢中使用的輔助語句,可以看作查詢時生成的臨時表
with mvtgeom AS ()
連線
應該總是提供連線條件
-
連線選項
-
inner join
-
left | right | full outer join
-
連線條件
-
natural
-
on <連線條件>
-
using (Col1, Col2 ...)
內連線
根據主鍵和外來鍵自然連線
外連線
包含沒有關聯到的行
組合查詢 UNION
同一個表的多個查詢,也可以不同表的查詢 (只要列資料格式相同,列名可以不同)
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_state IN ('IL','IN','MI')
UNION
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_name = 'Fun4All'
ORDER BY cust_name, cust_contact;