1. 程式人生 > >《SQL必知必會》筆記(施工中)

《SQL必知必會》筆記(施工中)

溫馨提示:本文程式碼全部以MySQL 5.7實現。

第7課 建立計算欄位

select concat(vend_name, '(', vend_country, ')')
	as vend_title
from vendors
order by vend_name;
select prod_id,
	quantity,
    item_price,
    quantity*item_price as expanded_price
from orderitems
where order_num=20008;

第13課 建立高階聯結

自聯結(SELF-JOIN)、自然聯結(NATURAL JOIN)和外聯結(OUTER JOIN)。

外聯結有兩種基本形式:左外聯結和右外聯結。

select customers.cust_id, orders.order_num
from customers left outer join orders
on customers.cust_id=orders.cust_id

小結:

本課是上一課的延續,首先講授瞭如何以及為什麼使用別名,然後討論不同的聯結型別以及每類聯結所使用的語法。我們還介紹瞭如何與聯結一起使用聚集函式,以及在使用聯結時應該注意的問題。

第14課 組合查詢

並(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';
小結:

這一課講授如何用UNION操作符來組合SELECT語句。利用UNION,可以把多條查詢的結果作為一條組合查詢返回,不管結果中有無重複。使用UNION可極大地簡化複雜的WHERE子句,簡化從多個表中檢索資料的工作。

第15課 插入資料

插入(INSERT)

15.1.1 插入完整的行

insert into customers (cust_id,
cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email)
value ('1000000006', 
'Toy Land', '123 Any Street', 'New York', 'NY', '11111', 'USA', NULL, NULL);
提示:INSERT通常只插入一行。
15.2 從一個表複製到另一個表

SELECT INTO(MySQL不支援)

create table custcopy as
select * from customers;
小結:

這一課介紹如何將行插入到資料庫中。我們學習了使用INSERT的幾種方法,為什麼要明確使用列名,如何用INSERT SELECT從其它表中匯入行,如何用SELECT INTO將行匯出到一個新表。下一課將講述如何使用UPDATE和DELETE進一步操作資料。

第16課 更新和刪除資料

16.1 更新資料(UPDATE)

#更新一列
update customers
set cust_email='[email protected]'
where cust_id='1000000005';
#更新多列
update customers
set cust_contact='Sam Roberts', cust_email='[email protected]'
where cust_id='1000000006';

16.2 刪除資料(DELETE)

-- 從表中刪除一行
delete from customers
where cust_id='1000000006';
刪除表中所有行(TRUNCATE TABLE)

小結:

這一課講述瞭如何使用UPDATE和DELETE語句處理表中的資料。我們學習了這些語句的語法,知道了它們可能存在的危險,瞭解了為什麼WHERE子句對UPDATE和DELETE語句很重要,還學習了為保證資料安全而應遵循的一些指導原則。


第17課 建立和操縱表

17.1 建立表(CREATE TABLE)

create table products
(
	prod_id char(10) not null,
	vend_id char(10) not null,
	prod_name char(254) not null,
	prod_price decimal(8,2) not null,
	prod_desc text(1000) null
);
17.1.3 指定預設值(DEFAULT)
create table orderitems
(
	order_num integer not null,
    order_item integer not null,
    prod_id char(10) not null,
    quantity integer not null default 1,
    item_price decimal(8,2) not null
);
將系統日期用作預設日期:DEFAULT CURRENT_DATE()

17.2 更新表(ALTER TABLE)

#增加列
alter table vendors
add vend_phone char(20);
# 刪除列
alter table vendors
drop column vend_phone;

17.3 刪除表(DROP TABLE)

drop table custcopy;
17.4 重命名錶
重命名錶(RENAME)

小結:

這一課介紹了幾條新的SQL語句。CREATE TABLE用來建立新表,ALTER TABLE用來更改表列(或其他諸如約束或索引等物件),而DROP TABLE用來完整地刪除一個表。這些語句必須小心使用,並且應該在備份後使用。由於這些語句的語法在不同的DBMS中有所不同,所以更詳細的資訊請參閱相應的DBMS文件。

第18課 使用檢視

18.2 建立檢視

建立檢視(CREATE VIEW)

刪除檢視(DROP VIEW)

18.2.1 利用檢視簡化複雜的聯結

建立一個名為ProductCustomers的檢視:

create view productcustomers as
select cust_name, cust_contact, prod_id
from customers, orders, orderitems
where customers.cust_id=orders.cust_id
and orderitems.order_num=orders.order_num;
從檢視中檢索:
select cust_name, cust_contact
from productcustomers
where prod_id='RGAN01';

18.2.2 用檢視重新格式化檢索出的資料
拼接欄位格式的例子

select concat(vend_name, '(', vend_country, ')')
	as vend_title
from vendors
order by vend_name;
# 把拼接轉換為檢視
create view vendorlocations as
select concat(vend_name, '(', vend_country, ')')
	as vend_title
from vendors;
# 從檢視中檢索
select *
from vendorlocations
18.2.3 用檢視過濾不想要的資料
create view CustomerEmailList as
select cust_id, cust_name, cust_email
from customers
where cust_email is not null;
# 從檢視中檢索
select *
from CustomerEmailList;
18.2.4 使用檢視與計算欄位
create view OrderItemsExpanded as
select order_num,
	prod_id,
    quantity,
    item_price,
    quantity*item_price as expanded_price
from orderitems;
# 從檢視中檢索
select *
from OrderItemsExpanded
where order_num=20008;
小結:

檢視為虛擬的表。它們包含的不是資料而是根據需要檢索資料的查詢。檢視提供了一種封裝SELECT語句的層次,可用來簡化資料處理,重新格式化或保護基礎資料。

第19課(第23課) 使用儲存過程(《MySQL必知必會》)

23.2 為什麼要使用儲存過程

有三個主要好處,即簡單、安全、高效能。

23.3 使用儲存過程
23.3.1 執行儲存過程(CALL PROCEDURE)

call productpricing(@pricelow,
@pricehigh,
@priceaverage);

23.3.2 建立儲存過程(CREATE PROCEDURE)

-- mysql命令列客戶機的分隔符
delimiter //	-- 告訴命令列實用程式使用//作為新的語句結束分隔符
create procedure productpricing()
	begin
		select avg(prod_price) as priceaverage
		from products;
	end //
delimiter ;		-- 恢復為原來的語句分隔符
-- 使用這個儲存過程
call productpricing();
23.3.3 刪除儲存過程(DROP PROCEDURE)
drop procedure productpricing;
23.3.4 使用引數
-- 建立帶引數的儲存過程
delimiter //
create procedure productpricing(
	out p1 decimal(8,2),
    out ph decimal(8,2),
    out pa decimal(8,2)
)
begin
	select min(prod_price)
    into p1
    from products;
    select max(prod_price)
    into ph
    from products;
    select avg(prod_price)
    into pa
	from products;
end //
delimiter ;
-- 使用帶引數的儲存過程
call productpricing(@pricelow,
					@pricehigh,
                    @priceaverage);
-- 顯示檢索出的3個值
select @pricehigh, @pricelow, @priceaverage;
-- 使用in和out引數
delimiter //
create procedure ordertotal(
	in onumber int,
    out ototal decimal(8,2)
)
begin
	select sum(item_price*quantity)
    from orderitems
    where order_num=onumber
    into ototal;
end //
delimiter ;
-- 呼叫並顯示
call ordertotal(20005, @total);
select @total;

23.3.5 建立智慧儲存過程

-- 建立儲存過程:獲得合計,把營業稅有條件地新增到合計,返回合計
-- 先刪除同名的儲存過程
drop procedure ordertatal;
-- Name: ordertotal
-- Parameters: 	onumber = order number
-- 				taxable = 0 if not taxable, 1 if taxable
delimiter //
create procedure ordertotal(
	in onumber int,
    in taxable boolean,
    out ototal decimal(8,2)
) comment 'Obtain order total, optionally adding tax'
begin
	-- declare定義區域性變數
	-- declare variable for total
    declare total decimal(8,2);
    -- declare tax percentage
    declare taxrate int default 6;
    -- get the order total
    select sum(item_price*quantity)
    from orderitems
    where order_num = onumber
    into total;
    -- is this taxable?
    if taxable then
		-- yes, so add taxrate to the total
        select total+(total/100*taxrate) into total;
	end if;
    -- and finally, save to out variable
    select total into ototal;
end //
delimiter ;
-- 呼叫並顯示
call ordertotal(20005, 1, @total);
select @total;

23.3.6 檢查儲存過程(SHOW CREATE PROCEDURE)

show create procedure ordertotal;
-- 獲得全部儲存過程詳細資訊
show procedure status;
-- 獲得該儲存過程詳細資訊
show procedure status like 'ordertotal';

小結:

這一課介紹了什麼是儲存過程,為什麼使用儲存過程。我們介紹了招行儲存過程的語法,使用儲存過程的一些方法。儲存過程是個相當重要的主題,一課內容無法全部涉及。各種DBMS對儲存過程的實現不一,你使用的DBMS可能提供了一些這裡提到的功能,也有其他未提及的功能,更詳細的介紹請參閱具體的DBMS文件。

第20課 管理事務處理

20.2 事務處理
20.2.1 使用ROLLBACK

delete from orders;
rollback;
20.2.2 使用COMMIT
start transaction;
delete from orderitems where order_num = 20009;
delete from orders where order_num = 20009;
commit;
20.2.3 使用保留點
-- 設定保留點
savepoint delete1;
-- 回退到保留點
rollback to delete1;
-- SQL Server例子,待以後改寫成MySQL的
begin transaction
insert into customes(cust_id, cust_name)
values('1000000010','Toys Emporium');
save transaction startorder;
insert into orders(order_num, order_date, cust_id)
values(20100,'2001/12/1','1000000010');
if @@error<>() rollback transaction startorder;
insert into orderitems(order_num, order_item, prod_id, quantity, item_price)
values(20100,1,'BR01',100,5.49);
if @@error<>() rollback transaction startorder;
insert into orderitems(order_num, order_item, prod_id, quantity, item_price)
values(20100,2,'BR03',100,10.99);
if @@error<>() rollback transaction startorder;
commit transaction
小結:

這一課介紹了事務是必須完整執行的SQL語句塊。我們學習瞭如何使用COMMIT和ROLLBACK語句對何時寫資料、何時撤銷進行明確的管理;還學習瞭如何使用保留點,更好地控制回退操作。事務處理是個相當重要的主題,一課內容無法全部涉及。各種DBMS對事務處理的實現不同,詳細內容請參考具體的DBMS文件。

第21課 使用遊標

遊標(CURSOR)

21.2 使用遊標
21.2.1 建立遊標

delimiter //
create procedure processorders()
begin
	declare ordernumbers cursor
	for
	select order_num from orders;
end //
delimiter ;

21.2.2 使用遊標(FETCH)

open ordernumbers
-- 從遊標中檢索第一行
delimiter //
create procedure processorders()
begin
	-- declare local variables
    declare o int;
    -- declare the cursor
	declare ordernumbers cursor
	for
	select order_num from orders;
    -- open the cursor
    open ordernumbers;
    -- get order number
    fetch ordernumbers into o;
    -- close the cursor
    close ordernumbers;
end //
delimiter ;
-- 迴圈檢索資料
delimiter //
create procedure processorders()
begin
	-- declare local variables
    declare done boolean default 0;
    declare o int;
    -- declare the cursor
	declare ordernumbers cursor
	for
	select order_num from orders;
    -- declare continue handler
    declare continue handler for sqlstate '02000' set done=1;
    -- open the cursor
    open ordernumbers;
    -- loop through all rows
    repeat
		-- get order number
        fetch ordernumbers into o;
	-- end of loop
    until done end repeat;
    -- close the cursor
    close ordernumbers;
end //
delimiter ;
-- 迴圈檢索資料並進行處理
delimiter //
create procedure processorders()
begin
	-- declare local variables
    declare done boolean default 0;
    declare o int;
    declare t decimal(8,2);
    -- declare the cursor
	declare ordernumbers cursor
	for
	select order_num from orders;
    -- declare continue handler
    declare continue handler for sqlstate '02000' set done=1;
    -- create a table to store the results
    create table if not exists ordertotals (order_num int, total decimal(8,2));
    -- open the cursor
    open ordernumbers;
    -- loop through all rows
    repeat
		-- get order number
        fetch ordernumbers into o;
        -- get the total for this order
        call ordertotal(o, 1, t);
        -- insert order and total into ordertotals
        insert into ordertotals(order_num, total)
        values(o, t);
	-- end of loop
    until done end repeat;
    -- close the cursor
    close ordernumbers;
end //
delimiter ;
-- 呼叫並顯示
call processorders();
select * from ordertotals;
21.2.3 關閉遊標
close ordernumbers
小結:

我們在本課講授了什麼是遊標,為什麼使用遊標。你使用的DBMS可能會提供某種形式的遊標,以及這裡沒有提及的功能。更詳細的內容請參閱具體的DBMS文件。

第22課 高階SQL特性
22.1 約束(CONSTRAINT)
>22.1.1 主鍵(PRIMARY KEY)

-- 建立主鍵
create table vendors
(
	vend_id			char(10)	not null primary key,
    vned_name		char(50)	not null,
    vend_address	char(50)	null,
    vend_city		char(50)	null,
    vend_state		char(50)	null,
    vend_zip		char(10)	null,
    vend_country	char(50)	null
);
-- 給表的vend_id列定義使其成為主鍵
alter table vendors
add constraint primary key(vend_id);
>22.1.2 外來鍵(FOREIGN KEY)
-- 定義外來鍵
create table orders
(
	order_num	integer		not null primary key,
    order_date	datetime	not null,
    cust_id		char(10)	not null references customers(cust_id)
);
-- 定義外來鍵
alter table orders
add constraint
foreign key(cust_id) references customers(cust_id);
>22.1.3 唯一約束(UNIQUE)

>22.1.4 檢查約束

-- 檢查約束保證所有物品的數量大於0
create table orders
(
	order_num	integer		not null,
    order_item	integer		not null,
    prod_id		char(10)	not null,
    quantity	integer		not null check(quantity>0),
    item_price	money		not null	-- money goes error in MySQL
);
-- 檢查名為gender的列只包含M或F
alter table customers
add constaint check(gender like '[MF]')	-- check goes error in MySQL
22.2 索引(INDEX)
-- 在Products表的產品名列上建立一個簡單索引
create index prod_name_ind
on products(prod_name);
22.3 觸發器(TRIGGER)
-- 建立觸發器
create trigger newproduct 
after insert on products
for each row select 'Product added';
-- 刪除觸發器
drop trigger newproduct;
-- 建立insert觸發器
create trigger neworder
after insert on orders
for each row select new.order_num;	-- 不允許觸發器返回order_num?
-- 測試此觸發器
insert into orders(order_date, cust_id)
values(now(), 10001);
-- 建立delete觸發器
delimiter //
create trigger deleteorder before delete on orders
for each row
begin
	insert into archive_orders(order_num, order_date, cust_id)
    values(old.order_num, old.order_date, old.cust_id);
end //	-- ?
delimiter ;
-- 建立update觸發器
create trigger updatevendor
before update on vendors
for each row set new.vend_state = upper(new.vend_state);
小結:

本課講授如何使用SQL的一些高階特性。約束是實施引用完整性的重要部分,索引可改善資料檢索的效能,觸發器可以用來執行執行前後的處理,安全選項可用來管理資料訪問。不同的DBMS可能會以不同的形式提供這些特性,更詳細的資訊請參閱具體的DBMS文件。


















相關推薦

SQL筆記施工

溫馨提示:本文程式碼全部以MySQL 5.7實現。 第7課 建立計算欄位 select concat(vend_name, '(', vend_country, ')') as vend_title from vendors order by vend_name;se

《深入理解Java虛擬機:JVM高級屬性與最佳實踐》讀書筆記更新

pen 內存區域 深度 span 進化 ria 最短 描述 core 第一章:走進Java 概述 Java技術體系 Java發展史 Java虛擬機發展史 1996年 JDK1.0,出現Sun Classic VM HotSpot VM, 它是 Sun JDK 和 Open

【模板】LCA最近公共祖先的各種寫法施工

def getchar() div 輸入輸出格式 memset while 樹結構 算法 its 以洛谷模板題(P3379)為例。 題目描述 如題,給定一棵有根多叉樹,請求出指定兩個點直接最近的公共祖先。 輸入輸出格式 輸入格式: 第一行包含三個正整數N、M、S,分別表

Wannafly交流賽1施工

fin ase 代碼 namespace pre nbsp stdio.h false rst A.有理數 簽到題:直接用floor函數就行了,詳細看代碼 #define debug #include<stdio.h> #include<math.h&g

Linux練習題-shell腳本編程基礎篇施工

從大到小 最大的 顯示 主機 練習題 shell腳本 空白 分享圖片 目錄備份 1、編寫腳本/root/bin/systeminfo.sh,顯示當前主機系統信息,包括主機名,IPv4地址,操作系統版本,內核版本,CPU型號,內存大小,硬盤大小2、編寫腳本/root/bin/

Linux練習題-文件查找施工

com ati mage cto -m image group linu title 1、查找/var目錄下屬主為root,且屬組為mail的所有文件find /var -u root -g mail2、查找/var目錄下不屬於root、lp、gdm的所有文件find /v

Linux練習題-文本處理工具sed施工

文件 文本處理 命令 linu roo ipv4 空白 ifconfig ipv4地址 1、刪除centos7系統/etc/grub2.cfg文件中所有以空白開頭的行行首的空白字符2、刪除/etc/fstab文件中所有以#開頭,後面至少跟一個空白字符的行的行首的#和空白字符

實驗九施工

1) assume cs:code, ds:data data segment db 12 db 0,0 ; 前一個位元組用於儲存商,後一個位元組用於儲存餘數 data ends code segment start: mov ax,data mov ds,

《思科路由器常用配置命令》學習筆記更新

1、檢視模式介紹 router> //使用者模式 router# //特權模式,在普通模式下輸入enable router(config)# //全域性模式,在特權模式下輸入configure terminal router(config-if)# //介面檢視,在全域性模

Matplotlib學習筆記更新

Matplotlib是最流行的Python底層繪相簿,主要做資料視覺化圖表,名字取材於MATLAB。 我覺得學習一門技術最好的辦法就是實踐它,所以我直接用例子來記錄,需要理解和記憶的地方我都加了註釋。 折線圖 #匯入需要用到的模組 from m

Numpy學習筆記更新

一個在Python中做科學計算的基礎庫,重在數值計算,也是大部分PYTHON科學計算庫的基礎庫,多用於在大型、多維陣列上執行數值運算。 陣列的定義 import numpy as np # numpy陣列的定義方法 a = np.arange

C++學習筆記更新

C和C++的區別 a. C是結構化的語言,面向過程,重點在於資料結構和演算法 b. C語言的API比較簡潔 c. C++包含了絕大部分C語言的功能,並且提供OOP(面向物件程式設計)和GP

專案案例之GitLab企業級程式碼管理倉庫施工

一.安項GitLab  主機名 IP 備註 特殊要求  git01    GIT客戶端  無  girlab &nb

《HTML&CSS設計與構建網站》學習筆記更新

第一章 結構 1.起始標籤和結束標籤,在元素起始標籤中有特性名稱和特性值。 2. <html></html>  <head></head>  <title></title> 3.HTML(HyperText Markup Langu

動態規劃: 揹包問題施工

參考自如下兩篇部落格: http://www.cnblogs.com/tanky_woo/archive/2010/07/31/1789621.html http://blog.csdn.net/insistgogo/article/details/11081025 一、

微信小程式例項——天氣預報開發筆記進行...

★ 背景 【提示】:正在補充更新中… 首先,附上一張效果圖. 之前就有關注過小程式的發展,感覺可以抽一點的時間來學習一下,通過官方文件以及提供的示例 Demo,發現興趣挺高,不失為一個

Deep learning筆記更新

在實踐中,alpha的一般取值為0:5,0:9 和0:99。和學習速率一樣,alpha也會隨著時間變化。一般初始值是一個較小的值,隨後會慢慢變大。隨著時間推移,改變alpha沒有收縮因子epsilon更重要。 自適應: AdaGrad 演算法,獨立地適應所有模型引數的學習速率,放縮每個引數反比於其所有梯度歷

Unity animator:StateMachineBehaviour的一點應用施工

cto 成員 err eric direct 其他 generic 條件 system Unity animator:StateMachineBehaviour的一點應用(施工中) 有什麽用 直奔主題,我們先講講作用,用法,再慢慢解釋 一個簡單的應用場景:Unity動畫狀態

Unity地面檢測方案總結施工

height physics lap lin bool doc set mono 4.3 Unity地面檢測方案總結(施工中) 1.簡單射線 在角色坐標(一般是腳底),發射一根向下的射線,長度大約為0.2,這樣是的確可以檢測到玩家是否在地面的,但只適用於簡單地形,如果你配置

SQL入門經典+SQL+視訊筆記之一

一、瞭解SQL 1. 關係型資料庫管理系統(RDBMS) 2. 結構化查詢語言(SQL)——關係型資料庫進行通訊的標準語言 3. ANSI標準——可移植性和易用性 4. 連線資料庫:CONNECT [