Become a Mochi that writes SQL!
SELECT ...
FROM...
1
Fumi 2022/04
fundamentals
RDBMS
Databases
Tables
Columns
Instance
Database
Tables
Columns
Tables
Columns
資料庫在
Google 雲端平台
的機器上
我們透過 metabase 等
工具連線,
取用資料
id | name | birth |
---|---|---|
1 | Andy | 2000-01-01 |
2 | Carter | 2001-12-31 |
users
結構
資料
id | name | birth |
---|---|---|
1 | Andy | 2000-01-01 |
2 | Carter | 2001-12-31 |
結構
id | name | birth |
---|---|---|
1 | Andy | 2000-01-01 |
2 | Carter | 2001-12-31 |
資料
column name | type |
---|---|
id | 整數 |
name | 字串 |
birth | 日期 |
SQL Basics
RDBMS
SELECT mobile, email FROM users LIMIT 3
撈取 users 的資料,只撈取 mobile 和 email 欄位
限回傳三筆資料
mobile | |
---|---|
0911222333 | abc@pklotcorp.com |
0911222444 | |
0911555666 | cdf@pklotcorp.com |
SELECT * FROM users LIMIT 3
撈取 users 的資料,撈取所有欄位(不建議正式情況使用)
id | mobile | ... | |
---|---|---|---|
2 | 0911222333 | abc@pklotcorp.com | ... |
3 | 0911222444 | ... | |
4 | 0911222456 | meowmeow@pklotcorp.com | ... |
SELECT mobile AS 手機, email AS 電子信箱
FROM users
LIMIT 3
欄位名稱可以取別名
手機 | 電子信箱 |
---|---|
0911222333 | abc@pklotcorp.com |
0911222444 | |
0911222456 | meowmeow@pklotcorp.com |
SELECT id, mobile, distributor_id
FROM users
WHERE mobile = '0911222333'
撈取手機為 0911222333 的使用者的資料
id | mobile | distributor_id |
---|---|---|
2 | 0911222333 | 1 |
3 | 0911222333 | 7 |
SELECT id, mobile, distributor_id
FROM users
WHERE mobile = '0911222333'
AND distributor_id = 1
撈取手機為 0911222333,通路 ID 為「1」的使用者的資料
id | mobile | distributor_id |
---|---|---|
2 | 0911222333 | 1 |
SELECT id, mobile, distributor_id
FROM users
WHERE created_at >= '2022-04-01'
撈取 2022-04-01 以後新增的使用者
id | mobile | distributor_id |
---|---|---|
2 | 0911222333 | 1 |
SELECT id, type, income_amount
FROM orders
WHERE income_amount > 2000
撈取金額大於 2000 的訂單
id | type | income_amount |
---|---|---|
33 | refueling | 2200 |
SELECT id, mobile, email
FROM users
WHERE mobile IN ('0911222333', '0911222456')
撈取手機在清單中(0911222333、0911222456)的資料
id | mobile | |
---|---|---|
2 | 0911222333 | abc@pklotcorp.com |
4 | 0911222456 | meowmeow@pklotcorp.com |
Aggregation
SELECT SUM(income_amount)
FROM orders
計算所有訂單金額的加總
SUM(income_amount) |
---|
36500 |
SELECT COUNT(1)
FROM orders
計算訂單總數
COUNT(1) |
---|
17 |
SELECT SUM(income_amount)
FROM orders
WHERE type = 'parking'
計算所有停車訂單金額的加總
SUM(income_amount) |
---|
17500 |
SELECT type, SUM(income_amount)
FROM orders
GROUP BY type
計算所有停車訂單金額的加總
type | SUM(income_amount) |
---|---|
parking | 17500 |
refueling | 18500 |
on_street_parking | 500 |
常見的聚合函式有:
Sorting
SELECT id, income_amount
FROM orders
WHERE type = 'parking'
ORDER BY income_amount
撈出所有停車訂單,按照金額排序(由小至大)
id | income_amount |
---|---|
1 | 20 |
2 | 30 |
SELECT id, income_amount
FROM orders
WHERE type = 'parking'
ORDER BY orders.income_amount DESC
撈出所有停車訂單,按照金額排序(由大至小)
id | income_amount |
---|---|
2 | 30 |
1 | 20 |
跨兩張表的資料如何處理?