作者paranoia5201 (社會黑暗、行路難)
看板Database
標題[SQL ] 考題語法請教
時間Tue Jun 11 23:52:24 2019
以下有兩個資料表:
> customers
C_ID Name City Address Phone
1 張一 台北市 XX路100號 02-123456789
2 王二 新竹縣 YY路200號 03-123456789
3 李三 高雄縣 ZZ路300號 07-123456789
> orders
O_ID OrderNO C_ID
1 2572 3
2 7375 3
3 1054 1
4 7520 1
5 1257 2
(1)找出每位客戶的訂單總數及最後那筆訂單編號。
我的解法:
select customers.Name, count(orders.C_ID) as OrderNumber,
max(OrderNO) as LastOrderNum
from customers, orders
where customers.C_ID = orders.C_ID
group by orders.C_ID
依照鄉民建議修改。
(2)修改訂單編號1257的客戶電話為03-87654321。
我的解法:
select customers.C_ID, customers.Name, customers.City, customers.Address,
replace (customers.Phone, '03-12345678', '03-87654321') as Phone
from orders, customers
where customers.C_ID = orders.C_ID and
orders.OrderNO = 1257
這裡用replace處理,但是不確定與update的差別,是指資料庫內容有無更新嗎?
(3)複製張一最後一筆訂單的資料,新增至orders(PK: O_ID)
我的解法:
想到的方式是create table然後全部重key,這樣很笨但是暫時查無好方法。
再麻煩各位解答了,感謝~~
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.194.164.43 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Database/M.1560268346.A.7B9.html
推 Phenomenon: MAX(OrderNumber) 試試 06/12 00:37
感謝建議,更新後解法修改在內文。
→ iv0813: update a 06/12 09:51
→ iv0813: set a.phone=03-87654321 06/12 09:51
→ iv0813: from customers a 06/12 09:52
→ iv0813: join order b on a.c_id =b.c_id 06/12 09:52
→ iv0813: and b.orderno=1257 06/12 09:53
本人資質駑鈍,有點看不懂,不過有更新語法在內文,還請指導。
※ 編輯: paranoia5201 (123.194.164.43 臺灣), 06/12/2019 11:41:36
※ 編輯: paranoia5201 (123.194.164.43 臺灣), 06/12/2019 11:44:39
推 far0802: 2的解法你可以去google update join 06/12 13:25
推 far0802: 3的解法則是1的解法再增加where name='張一',再insert 06/12 13:27
→ far0802: 回orders這張表 06/12 13:27
→ far0802: 2是要你做update,你用select是沒有作用的 06/12 13:28
→ far0802: 建議你可以先google了解DML,DQL的差異 06/12 13:33
→ funk6478: replace只作用在你查詢的結果 不會修改DB裡的值 06/12 17:05
→ funk6478: 第2題看題目敘述 應該是要你用update 06/12 17:10
推 hmsDEBBIE: 你串表要from a join b on a.ID=b.ID 而不是直接寫from 06/16 22:19
→ hmsDEBBIE: a, b 06/16 22:19
→ hmsDEBBIE: 你更新在內文的寫錯了 推iv大寫的 06/16 22:20