sql
🧭 Overview:SQL 的整体脉络
SQL(Structured Query Language)是操作关系型数据库(RDBMS)的语言。 与编程语言不同,SQL 是 声明式语言(Declarative Language): 👉 你告诉数据库“想要什么结果”,数据库自己决定“怎么做”。
我们可以把学习 SQL 看作一个逐步扩展的层级体系:
| 层级 | 内容 | 目标 |
|---|---|---|
| 基础查询层 | SELECT / WHERE / ORDER BY | 从表中取出你要的数据 |
| 条件逻辑层 | AND / OR / NOT / IN / BETWEEN / LIKE | 构造灵活的筛选条件 |
| 聚合统计层 | COUNT() / SUM() / GROUP BY / HAVING | 对数据分组、计算统计值 |
| 多表关系层 | 各类 JOIN、UNION | 让多个表形成逻辑上的整体 |
| 数据操作层 | INSERT / UPDATE / DELETE | 修改数据库内容 |
| 高级控制层 | CASE / NULL 处理 / 存储过程 | 应对复杂业务逻辑 |
📘 SQL 简介
SQL 是关系数据库的“通用语言”,几乎所有主流数据库(MySQL、PostgreSQL、SQL Server、Oracle)都遵循 SQL 标准。
🧩 核心功能分类:
- 数据查询语言(DQL):
SELECT - 数据操作语言(DML):
INSERT、UPDATE、DELETE - 数据定义语言(DDL):
CREATE、ALTER、DROP - 数据控制语言(DCL):
GRANT、REVOKE
💡 理解思路: SQL 就像一整套“数据库的语法系统”,掌握了它,你就能与任何数据库对话。
📝 SQL 语法规则
🧩 结构规则
- 每条语句通常以分号
;结束(某些系统可省略) - SQL 关键字不区分大小写,但字符串内容区分
- 语句可换行,可缩进
💡 推荐书写规范:
1
2
3
4
SELECT name, age
FROM students
WHERE age > 18
ORDER BY name;
⚠️ 常见错误:
- 忘记加分号(在多语句执行环境中)
- 把字符串写成未加引号的形式
🔍 SQL SELECT
🧩 作用:从表中选取数据。
1
SELECT 列1, 列2 FROM 表名;
💡 举例:
1
SELECT name, age FROM students;
⚠️ 注意事项:
SELECT *选取所有列,但效率较低。- 推荐明确列名,尤其在多表查询时。
🧠 延伸理解: SELECT 并不改变数据库,它只是创建一个虚拟的结果表(Result Set),这个结果可以再被进一步筛选、排序、聚合。
🔁 SQL SELECT DISTINCT
🧩 作用:去重,返回唯一的行。
💡 示例:
1
SELECT DISTINCT class FROM students;
⚠️ 误区提醒: DISTINCT 作用于整行,不是单列。 如下:
1
SELECT DISTINCT name, age FROM students;
只有 name 和 age 都相同 才算重复。
✅ SQL WHERE
🧩 作用:按条件过滤记录。
1
SELECT * FROM students WHERE age > 18;
💡 逻辑顺序: SQL 实际的执行顺序中,WHERE 在 GROUP BY 之前执行。 可以理解为:
1
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY
⚠️ 常见错误: 不能在 WHERE 中使用聚合函数(如 AVG()),那是 HAVING 的工作。
🔽 SQL ORDER BY
🧩 作用:对结果排序。
1
SELECT * FROM students ORDER BY age DESC, name ASC;
💡 小技巧:
ASC:升序(默认)DESC:降序- 可用列序号排序(不推荐):
ORDER BY 2
⚠️ 性能提醒: 排序需要额外计算资源,大数据量时应在索引列上排序。
🔗 SQL AND / OR / NOT
🧩 作用:构造复杂的条件逻辑。
1
2
SELECT * FROM students
WHERE (age > 18 AND gender = 'M') OR city = 'Beijing';
💡 优先级规律: NOT > AND > OR 因此最好使用括号明确逻辑。
🚫 SQL NULL Values
🧩 NULL 的本质: NULL ≠ 空字符串,也 ≠ 0,它代表“未知”或“不存在”。
💡 判断方式:
1
2
WHERE column IS NULL;
WHERE column IS NOT NULL;
⚠️ 常见陷阱:
column = NULL永远返回 false- 聚合函数(如
AVG())会忽略 NULL 值
🧠 延伸理解: NULL 会影响比较运算,因此 SQL 提供了 COALESCE() 等函数将 NULL 转换为默认值。
✏️ SQL UPDATE
🧩 作用:修改已有数据。
1
UPDATE students SET age = 21 WHERE name = 'Alice';
⚠️ 高危提醒: 忘写 WHERE 会更新整张表! 所以写完 SQL 前先 mentally simulate 一下执行范围。
🗑️ SQL DELETE
🧩 作用:删除记录。
1
DELETE FROM students WHERE age < 10;
⚠️ 常见混淆:
DELETE删除数据行,但保留表结构DROP TABLE删除整个表TRUNCATE TABLE删除表内所有数据但保留结构(速度更快)
📊 SQL Aggregate Functions
🧩 聚合函数对多行数据执行计算,返回单值结果。
| 函数 | 说明 |
|---|---|
COUNT() | 统计行数 |
SUM() | 求和 |
AVG() | 平均值 |
MIN() / MAX() | 最小/最大值 |
💡 示例:
1
2
SELECT COUNT(*) AS 学生数, AVG(score) AS 平均分
FROM students;
📂 SQL GROUP BY
🧩 作用:把结果集按某列分组。
💡 示例:
1
2
3
SELECT class, AVG(score)
FROM students
GROUP BY class;
表示“按班级计算平均分”。
⚠️ 常见错误:
- 非聚合列必须出现在
GROUP BY中,否则 SQL 不知道如何分组。 GROUP BY后面不能直接用聚合函数。
🧠 思维提示: 可以把 GROUP BY 想成 Excel 的“分类汇总”。
🎯 SQL HAVING
🧩 作用:在分组后再过滤结果。
💡 区别对比:
| 比较项 | WHERE | HAVING |
|---|---|---|
| 执行阶段 | 分组前 | 分组后 |
| 可用聚合函数 | ❌ 否 | ✅ 是 |
| 常用于 | 原始行过滤 | 统计结果过滤 |
💡 示例:
1
2
3
4
SELECT class, AVG(score)
FROM students
GROUP BY class
HAVING AVG(score) > 80;
🤝 SQL JOINS
🧩 核心思想: JOIN 让不同表的数据通过关联字段连接起来。
| 类型 | 返回内容 |
|---|---|
| INNER JOIN | 两表中匹配的记录(交集) |
| LEFT JOIN | 左表全部 + 匹配的右表行 |
| RIGHT JOIN | 右表全部 + 匹配的左表行 |
| FULL JOIN | 两表并集,匹配不到的补 NULL |
💡 示例:
1
2
3
SELECT s.name, c.course_name
FROM students s
INNER JOIN courses c ON s.id = c.student_id;
🧠 可视化记忆: 把两张表想成两个圆形——INNER JOIN 是交集,LEFT JOIN 是保留左圆。
⚡ SQL UNION / UNION ALL
🧩 作用:合并两个 SELECT 结果。
💡 示例:
1
2
3
SELECT name FROM students_2024
UNION ALL
SELECT name FROM students_2025;
⚠️ 要点:
UNION自动去重UNION ALL保留重复行(更快)- 两个 SELECT 必须列数与类型相同
🧠 SQL CASE
🧩 作用:条件表达式,类似 if-else。
1
2
3
4
5
6
7
SELECT name,
CASE
WHEN score >= 90 THEN 'A'
WHEN score >= 60 THEN 'B'
ELSE 'C'
END AS grade
FROM students;
💡 用途场景:
- 转换数值为分类标签
- 处理复杂条件逻辑
- 在统计中动态分组
🧩 SQL Null Functions
💡 常用函数:
COALESCE(a, b)→ 如果 a 是 NULL,返回 bISNULL(a, b)→ SQL Server 专用IFNULL(a, b)→ MySQL 专用
示例:
1
SELECT COALESCE(score, 0) AS real_score FROM students;
🧾 SQL Stored Procedures
🧩 作用:预编译 SQL 逻辑,像函数一样复用。
💡 示例:
1
2
CREATE PROCEDURE GetTopStudents AS
SELECT name, score FROM students WHERE score > 90;
🧠 用途: 封装复杂逻辑,减少重复查询语句,提升执行效率。
💬 SQL Comments
💡 两种写法:
1
2
-- 单行注释
/* 多行注释 */
⚠️ 建议: 在教学或协作场景中,注释对 SQL 可读性非常重要。
🧮 SQL Operators
🧩 常见类型:
| 类型 | 示例 | 功能 |
|---|---|---|
| 算术运算符 | + - * / % | 数值运算 |
| 比较运算符 | = <> > < >= <= | 判断关系 |
| 逻辑运算符 | AND OR NOT | 条件组合 |
💡 提示: <> 表示“不等于”,而不是 !=(尽管很多数据库兼容)。
📚 总结:SQL 的学习顺序
- 取数据:
SELECT/WHERE/ORDER BY - 算数据:
COUNT()/SUM()/GROUP BY/HAVING - 连数据:
JOIN/UNION - 改数据:
INSERT/UPDATE/DELETE - 控制逻辑:
CASE/NULL处理 / 存储过程
掌握以上层次,就能从“会查数据”进阶到“能用 SQL 解决业务逻辑”。
最后,我在这里放一张关键词表:
| Keyword | Description |
|---|---|
| ADD | Adds a column in an existing table |
| ADD CONSTRAINT | Adds a constraint after a table is already created |
| ALL | Returns true if all of the subquery values meet the condition |
| ALTER | Adds, deletes, or modifies columns in a table, or changes the data type of a column in a table |
| ALTER COLUMN | Changes the data type of a column in a table |
| ALTER TABLE | Adds, deletes, or modifies columns in a table |
| AND | Only includes rows where both conditions is true |
| ANY | Returns true if any of the subquery values meet the condition |
| AS | Renames a column or table with an alias |
| ASC | Sorts the result set in ascending order |
| BACKUP DATABASE | Creates a back up of an existing database |
| BETWEEN | Selects values within a given range |
| CASE | Creates different outputs based on conditions |
| CHECK | A constraint that limits the value that can be placed in a column |
| COLUMN | Changes the data type of a column or deletes a column in a table |
| CONSTRAINT | Adds or deletes a constraint |
| CREATE | Creates a database, index, view, table, or procedure |
| CREATE DATABASE | Creates a new SQL database |
| CREATE INDEX | Creates an index on a table (allows duplicate values) |
| CREATE OR REPLACE VIEW | Updates a view |
| CREATE TABLE | Creates a new table in the database |
| CREATE PROCEDURE | Creates a stored procedure |
| CREATE UNIQUE INDEX | Creates a unique index on a table (no duplicate values) |
| CREATE VIEW | Creates a view based on the result set of a SELECT statement |
| DATABASE | Creates or deletes an SQL database |
| DEFAULT | A constraint that provides a default value for a column |
| DELETE | Deletes rows from a table |
| DESC | Sorts the result set in descending order |
| DISTINCT | Selects only distinct (different) values |
| DROP | Deletes a column, constraint, database, index, table, or view |
| DROP COLUMN | Deletes a column in a table |
| DROP CONSTRAINT | Deletes a UNIQUE, PRIMARY KEY, FOREIGN KEY, or CHECK constraint |
| DROP DATABASE | Deletes an existing SQL database |
| DROP DEFAULT | Deletes a DEFAULT constraint |
| DROP INDEX | Deletes an index in a table |
| DROP TABLE | Deletes an existing table in the database |
| DROP VIEW | Deletes a view |
| EXEC | Executes a stored procedure |
| EXISTS | Tests for the existence of any record in a subquery |
| FOREIGN KEY | A constraint that is a key used to link two tables together |
| FROM | Specifies which table to select or delete data from |
| FULL OUTER JOIN | Returns all rows when there is a match in either left table or right table |
| GROUP BY | Groups the result set (used with aggregate functions: COUNT, MAX, MIN, SUM, AVG) |
| HAVING | Used instead of WHERE with aggregate functions |
| IN | Allows you to specify multiple values in a WHERE clause |
| INDEX | Creates or deletes an index in a table |
| INNER JOIN | Returns rows that have matching values in both tables |
| INSERT INTO | Inserts new rows in a table |
| INSERT INTO SELECT | Copies data from one table into another table |
| IS NULL | Tests for empty values |
| IS NOT NULL | Tests for non-empty values |
| JOIN | Joins tables |
| LEFT JOIN | Returns all rows from the left table, and the matching rows from the right table |
| LIKE | Searches for a specified pattern in a column |
| LIMIT | Specifies the number of records to return in the result set |
| NOT | Only includes rows where a condition is not true |
| NOT NULL | A constraint that enforces a column to not accept NULL values |
| OR | Includes rows where either condition is true |
| ORDER BY | Sorts the result set in ascending or descending order |
| OUTER JOIN | Returns all rows when there is a match in either left table or right table |
| PRIMARY KEY | A constraint that uniquely identifies each record in a database table |
| PROCEDURE | A stored procedure |
| RIGHT JOIN | Returns all rows from the right table, and the matching rows from the left table |
| ROWNUM | Specifies the number of records to return in the result set |
| SELECT | Selects data from a database |
| SELECT DISTINCT | Selects only distinct (different) values |
| SELECT INTO | Copies data from one table into a new table |
| SELECT TOP | Specifies the number of records to return in the result set |
| SET | Specifies which columns and values that should be updated in a table |
| TABLE | Creates a table, or adds, deletes, or modifies columns in a table, or deletes a table or data inside a table |
| TOP | Specifies the number of records to return in the result set |
| TRUNCATE TABLE | Deletes the data inside a table, but not the table itself |
| UNION | Combines the result set of two or more SELECT statements (only distinct values) |
| UNION ALL | Combines the result set of two or more SELECT statements (allows duplicate values) |
| UNIQUE | A constraint that ensures that all values in a column are unique |
| UPDATE | Updates existing rows in a table |
| VALUES | Specifies the values of an INSERT INTO statement |
| VIEW | Creates, updates, or deletes a view |
| WHERE | Filters a result set to include only records that fulfill a specified condition |