SQL指令語法速查手冊(六)

INSERT INTO 插入資料
INSERT INTO TABLE(欄位,欄位...)
VALUES (值,值...)
範例
INSERT INTO sample(ID,name,price)
values(001,'cola',30);
INSERT INTO sample(ID,name)
values(001,'tea');
上述SQL敘述,沒有指定price欄位,所以自動補上NULL(空值)。
將SELECT的結果輸出到另一個資料表-INSERT INTO
INSERT INTO TABLE1(欄位,欄位...)
SELECT (欄位名稱) (欄位名稱)...
FROM (表格名稱)
WHERE (搜尋條件)
範例
INSERT INTO people(ID,name,age) SELECT * FROM people;

INSERT INTO people SELECT * FROM people;
INSERT INTO people(age) SELECT sum(age) FROM people;
UPDATE 更新資料
UPDATE TABLE
SET 欄位名稱=更新值, 欄位名稱=更新值...
WHERE (搜尋條件)
範例
UPDATE people set age=34 WHERE ID=6;
DELETE 刪除資料
DELETE FROM TABLE
WHERE (搜尋條件)
 DELETE語法是指定資料表然後刪除符合條件的值。通常使用時,會透過WHERE加入條件判斷,並刪除指定資料。如果沒有加上WHERE指定搜尋條件的情況,則會將資料表中所有資料刪除。另外TRUNCATE TABLE語法也是將資料表清空的指令。
範例
DELETE FORM people WHERE ID=7;

SQL指令語法速查手冊(五)

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;