SELECT 從資料表取得資料
SELECT (欄位名稱) (欄位名稱)....
FROM (表格名稱)
WHERE (搜尋條件)
GROUP BY [HAVING ] (欄位名稱)
ORDER BY (欄位名稱)
範例:
SELECT * FORM store;
SELECT name,price,cost FROM store;
SELECT name,price,cost FROM store WHERE price<50;
使用排序順序的查詢-ORDER BY
SELECT name,price,cost FROM store WHERE price<50
ORDER BY cost;
使用別名查詢
SELECT name,price,cost,price-cost FROM store;
SELECT name,price,cost,price-cost profit FROM store;
FROM 指定資料表
SELECT ....
FROM TABLE [TABLE2] [TABLE3]....
範例:
SELECT student.name,homework.work FROM homework,student;
SELECT student.name,homework.work
FROM homework,student W=student.ID;
WHERE 指定條件
SELECT ...
FROM TABLE
WHERE (搜尋條件) [OR ,AND] ...
範例:
SELECT * FROM student WHERE height>=170;
SELECT * FROM student WHERE height<170 OR weight<70;
SELECT * FROM student WHERE height between 170 AND 190;
GROUP BY 將資料群組化
SELECT ...
FROM TABLE
GROUP BY (欄位名稱)
在寫GROUP BY 的語法時必須注意,使用的函數都必須是群組計算的概念。如果使用sum函數,將特定欄位計算得出值,就會是群組的總和,而不會是所有的值總和。在群組的語法後面加上WITH ROLLUP可以計算出所有群組的總和,指令中該語法最後一排會出現匯總的值,而該會總列的列名會被指定為NULL。
範例:
SELECT * FROM store GROUP BY class;
SELECT class,sum(price),sum(cost) FROM store
GROUP BY class;
SELECT class,sum(price),sum(cost) FROM store
GROUP BY class WITH ROLLUP;
HAVING 對群組化的資料設定條件
SELECT...
FROM TABLE
GROUP BY (欄位名稱)
HAVING (搜尋條件)
GROUP BY 語法群組化的資料取得時,如果要再進行搜尋條件設定的話,就必須使用HAVING語法。在沒有群組話之前的資料是透過WHERE語法來進行搜尋設定,而在群組化之後的資料就必須透過HAVING語法才能進行搜尋。
範例:
SELECT class,sum(price),sum(cost) FROM store
GROUP BY class HAVING sum(cost)<40;
SELECT class,AVG(price),AVG(cost) FROM store
GROUP BY class;
ORDER BY 指定結果的排列方式
SELECT...
FROM TABLE
ORDER BY (欄位名稱)
ASC 由小到大
DESC 由大到小
範例:
SELECT * FROM ball ORDER BY price DESC;
SELECT * FROM ball ORDER BY quantity ASC;
LIMIT 限制結果筆數
SELECT...
FROM TABLE
LIMIT (資料筆數)
或
LIMIT [開始筆數],[資料筆數]
當我們同時使用WHERE語法指定條件與LIMIT指定筆數時,WHERE指定的條件判斷會被執行,執行完成才會執行LIMIT語法。也就是說WHERE與LIMIT的執行優先順序為WHERE優先於LIMIT。
範例:
SELECT * FROM people limit 5;
SELECT * FROM people limit 3,4;