[上課筆記] PHP與SQL 第二彈

前置作業(作業):建立三個table
1. 客戶資料 - 欄位:客戶帳號、密碼、姓名
CREATE TABLE w03_customer (c_id int(10) AUTO_INCREMENT, c_account text, c_password text, c_name text, PRIMARY KEY(c_id))
# crate table 客戶資料表 (索引欄 整數(長度10), 客戶帳號 文字串, 密碼 文字串, 姓名 文字串, primary key(索引值));

2. 訂單資料 - 欄位:產品編號、購買數量、客戶編號、訂購時間
CREATE TABLE w03_order (o_id int(10) AUTO_INCREMENT, o_product_sn text, o_buy_num int(10), o_customer_sn text, c_order_time DATETIME, PRIMARY KEY(o_id))
# crate table 訂單資料表 (索引攔 整數(長度10), 產品編號 文字串, 購買數量 整數(長度10), 客戶編號 文字串, 訂單時間 日時, primary key(索引值));

3. 產品資料 - 欄位:產品名稱、產品金額、產品介紹
CREATE TABLE w03_product (p_id int(10) AUTO_INCREMENT, p_product_name text, p_product_price decimal(10.2), p_product_desc text, PRIMARY KEY(p_id))
# crate table 訂單資料表 (索引攔 整數(長度10), 產品名 文字串, 產品價格 浮點數(長度10,小數點2), 產品介紹 文字串, primary key(索引值));

4. 新增TABLE 1 與 TABLE 3 的內容資料,請都使用語法建立
(新增4筆資料 for table 1 & 新增5筆資料 for table 5)
INSERT INTO w03_customer VALUES (null, "user1", "pwd1", "mr.A"), (null, "user2", "pwd2", "mr.B"), (null, "user3", "pwd3", "mr.C"), (null, "user4", "pwd4", "mr.D")
#insert into 資料表 values (空值,帳號,密碼,名稱), (空值,帳號,密碼,名稱), (空值,帳號,密碼,名稱), (空值,帳號,密碼,名稱);

INSERT INTO w03_product VALUES (null, "product1", "100", "it's 100 dollors"), (null, "product2", "200", "it's 200 dollors"), (null, "product3", "300", "it's 300 dollors"),(null, "product4", "400", "it's 400 dollors"), (null, "product5", "500", "it's 500 dollors")
#insert into 資料表 values (空值,產名,價格,描述), (空值,產名,價格,描述), (空值,產名,價格,描述), (空值,產名,價格,描述), (空值,產名,價格,描述);



5. 接著手動建立兩筆資料於w03_order內。這裡要注意一下"產品編號"跟客戶編號"必須是已存在於另兩個table內。

目前資料結果為

w03_customer
c_id
c_account
c_password
c_name
1
user1
pwd1
mr.A
2
user2
pwd2
mr.B
3
user3
pwd3
mr.C
4
user4
pwd4
mr.D

w03_product
1
product1
100
it's 100 dollors
2
product2
200
it's 200 dollors
3
product3
300
it's 300 dollors
4
product4
400
it's 400 dollors
5
product5
500
it's 500 dollors

w03_order
1
2
10
2
2018-10-15 00:00:00
2
4
5
4
2018-10-15 00:00:00

w03_order當中,o_product_sno_customer_sn都是另外兩個的索引值(外鍵)

嘗試列出所有顯示 (a,b,c為臨時變數)
select * from w03_customer a, w03_product b, w03_order c where 1

會發現很多不存在的訂單組合,因此縮小範圍(利用外鍵與內鍵做比對)
select * from w03_customer a, w03_product b, w03_order c 
where a.c_id = c.o_customer_sn
and b.p_id = c.o_product_sn

2
user2
pwd2
mr.B
2
product2
200
it's 200 dollors
1
2
10
2
2018-10-15 00:00:00
4
user4
pwd4
mr.D
4
product4
400
it's 400 dollors
2
4
5
4
2018-10-15 00:00:00

這樣就是有效的關聯組合(僅兩筆)







-------------------------------------
(暫存)(老師版)(原指令)

select * from t1_cut a, t2_itme b, t3_log c where 1
select * from t1_cut a, t2_itme b, t3_log c where a.t1_seq = c.t3_t1 and b.t2_seq = c.t3_t1



留言