SQL速記表
基本的 SQL常見的查詢和操作語法:
基本 SQL 語法
1. 選擇數據(SELECT)
SELECT column1, column2, ...
FROM table_name
WHERE condition;
SELECT * FROM table_name;
- 選擇表中的所有欄位WHERE
- 用於過濾條件DISTINCT
- 過濾重複數據:SELECT DISTINCT column1 FROM table_name;
2. 插入數據(INSERT INTO)
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
- 插入多行:
INSERT INTO table_name (column1, column2, ...) VALUES (value1a, value2a), (value1b, value2b);
3. 更新數據(UPDATE)
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
- 請注意:若不加
WHERE
條件,將會更新表中的所有行。
4. 刪除數據(DELETE)
DELETE FROM table_name
WHERE condition;
- 若不加
WHERE
條件,將會刪除表中的所有行。
高級 SQL 查詢
1. 條件查詢(WHERE、AND、OR)
SELECT column1, column2
FROM table_name
WHERE condition1 AND condition2
OR condition3;
2. 範圍查詢(BETWEEN)
SELECT column1, column2
FROM table_name
WHERE column1 BETWEEN value1 AND value2;
3. 模糊查詢(LIKE)
SELECT column1, column2
FROM table_name
WHERE column1 LIKE 'pattern%';
%
表示任意數量字符,_
表示單個字符。
4. 空值檢查(IS NULL / IS NOT NULL)
SELECT column1, column2
FROM table_name
WHERE column1 IS NULL;
5. 排序(ORDER BY)
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC, column2 DESC;
ASC
- 升序(默認),DESC
- 降序
6. 分組(GROUP BY 和 HAVING)
SELECT column1, COUNT(*)
FROM table_name
GROUP BY column1
HAVING COUNT(*) > 1;
7. 聚合函數
COUNT(column)
- 計數SUM(column)
- 總和AVG(column)
- 平均MAX(column)
- 最大值MIN(column)
- 最小值
表操作
1. 創建表(CREATE TABLE)
CREATE TABLE table_name (
column1 datatype PRIMARY KEY,
column2 datatype NOT NULL,
column3 datatype DEFAULT value
);
2. 修改表結構(ALTER TABLE)
- 添加欄位:
ALTER TABLE table_name ADD column_name datatype;
- 修改欄位類型:
ALTER TABLE table_name MODIFY column_name new_datatype;
- 刪除欄位:
ALTER TABLE table_name DROP COLUMN column_name;
3. 刪除表(DROP TABLE)
DROP TABLE table_name;
4. 清空表(TRUNCATE TABLE)
TRUNCATE TABLE table_name;
鏈結(JOIN)
1. 內聯接(INNER JOIN)
SELECT table1.column1, table2.column2
FROM table1
INNER JOIN table2 ON table1.common_column = table2.common_column;
2. 左聯接(LEFT JOIN)
SELECT table1.column1, table2.column2
FROM table1
LEFT JOIN table2 ON table1.common_column = table2.common_column;
3. 右聯接(RIGHT JOIN)
SELECT table1.column1, table2.column2
FROM table1
RIGHT JOIN table2 ON table1.common_column = table2.common_column;
4. 全聯接(FULL OUTER JOIN)
SELECT table1.column1, table2.column2
FROM table1
FULL OUTER JOIN table2 ON table1.common_column = table2.common_column;
子查詢和複合查詢
1. 子查詢(Subquery)
SELECT column1
FROM table_name
WHERE column2 = (SELECT column2 FROM another_table WHERE condition);
2. UNION 和 UNION ALL
UNION
- 合併結果集,去重UNION ALL
- 合併結果集,不去重
SELECT column1 FROM table1
UNION
SELECT column1 FROM table2;
索引和性能優化
1. 創建索引(CREATE INDEX)
CREATE INDEX index_name ON table_name (column1, column2);
- 唯一索引:
CREATE UNIQUE INDEX index_name ON table_name (column);
2. 刪除索引(DROP INDEX)
DROP INDEX index_name ON table_name;