Post

sql

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对数据分组、计算统计值
多表关系层各类 JOINUNION让多个表形成逻辑上的整体
数据操作层INSERT / UPDATE / DELETE修改数据库内容
高级控制层CASE / NULL 处理 / 存储过程应对复杂业务逻辑

📘 SQL 简介

SQL 是关系数据库的“通用语言”,几乎所有主流数据库(MySQL、PostgreSQL、SQL Server、Oracle)都遵循 SQL 标准。

🧩 核心功能分类:

  1. 数据查询语言(DQL)SELECT
  2. 数据操作语言(DML)INSERTUPDATEDELETE
  3. 数据定义语言(DDL)CREATEALTERDROP
  4. 数据控制语言(DCL)GRANTREVOKE

💡 理解思路: 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 实际的执行顺序中,WHEREGROUP 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

🧩 作用:在分组后再过滤结果。

💡 区别对比

比较项WHEREHAVING
执行阶段分组前分组后
可用聚合函数❌ 否✅ 是
常用于原始行过滤统计结果过滤

💡 示例

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,返回 b
  • ISNULL(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 的学习顺序

  1. 取数据SELECT / WHERE / ORDER BY
  2. 算数据COUNT() / SUM() / GROUP BY / HAVING
  3. 连数据JOIN / UNION
  4. 改数据INSERT / UPDATE / DELETE
  5. 控制逻辑CASE / NULL 处理 / 存储过程

掌握以上层次,就能从“会查数据”进阶到“能用 SQL 解决业务逻辑”。

最后,我在这里放一张关键词表:

KeywordDescription
ADDAdds a column in an existing table
ADD CONSTRAINTAdds a constraint after a table is already created
ALLReturns true if all of the subquery values meet the condition
ALTERAdds, deletes, or modifies columns in a table, or changes the data type of a column in a table
ALTER COLUMNChanges the data type of a column in a table
ALTER TABLEAdds, deletes, or modifies columns in a table
ANDOnly includes rows where both conditions is true
ANYReturns true if any of the subquery values meet the condition
ASRenames a column or table with an alias
ASCSorts the result set in ascending order
BACKUP DATABASECreates a back up of an existing database
BETWEENSelects values within a given range
CASECreates different outputs based on conditions
CHECKA constraint that limits the value that can be placed in a column
COLUMNChanges the data type of a column or deletes a column in a table
CONSTRAINTAdds or deletes a constraint
CREATECreates a database, index, view, table, or procedure
CREATE DATABASECreates a new SQL database
CREATE INDEXCreates an index on a table (allows duplicate values)
CREATE OR REPLACE VIEWUpdates a view
CREATE TABLECreates a new table in the database
CREATE PROCEDURECreates a stored procedure
CREATE UNIQUE INDEXCreates a unique index on a table (no duplicate values)
CREATE VIEWCreates a view based on the result set of a SELECT statement
DATABASECreates or deletes an SQL database
DEFAULTA constraint that provides a default value for a column
DELETEDeletes rows from a table
DESCSorts the result set in descending order
DISTINCTSelects only distinct (different) values
DROPDeletes a column, constraint, database, index, table, or view
DROP COLUMNDeletes a column in a table
DROP CONSTRAINTDeletes a UNIQUE, PRIMARY KEY, FOREIGN KEY, or CHECK constraint
DROP DATABASEDeletes an existing SQL database
DROP DEFAULTDeletes a DEFAULT constraint
DROP INDEXDeletes an index in a table
DROP TABLEDeletes an existing table in the database
DROP VIEWDeletes a view
EXECExecutes a stored procedure
EXISTSTests for the existence of any record in a subquery
FOREIGN KEYA constraint that is a key used to link two tables together
FROMSpecifies which table to select or delete data from
FULL OUTER JOINReturns all rows when there is a match in either left table or right table
GROUP BYGroups the result set (used with aggregate functions: COUNT, MAX, MIN, SUM, AVG)
HAVINGUsed instead of WHERE with aggregate functions
INAllows you to specify multiple values in a WHERE clause
INDEXCreates or deletes an index in a table
INNER JOINReturns rows that have matching values in both tables
INSERT INTOInserts new rows in a table
INSERT INTO SELECTCopies data from one table into another table
IS NULLTests for empty values
IS NOT NULLTests for non-empty values
JOINJoins tables
LEFT JOINReturns all rows from the left table, and the matching rows from the right table
LIKESearches for a specified pattern in a column
LIMITSpecifies the number of records to return in the result set
NOTOnly includes rows where a condition is not true
NOT NULLA constraint that enforces a column to not accept NULL values
ORIncludes rows where either condition is true
ORDER BYSorts the result set in ascending or descending order
OUTER JOINReturns all rows when there is a match in either left table or right table
PRIMARY KEYA constraint that uniquely identifies each record in a database table
PROCEDUREA stored procedure
RIGHT JOINReturns all rows from the right table, and the matching rows from the left table
ROWNUMSpecifies the number of records to return in the result set
SELECTSelects data from a database
SELECT DISTINCTSelects only distinct (different) values
SELECT INTOCopies data from one table into a new table
SELECT TOPSpecifies the number of records to return in the result set
SETSpecifies which columns and values that should be updated in a table
TABLECreates a table, or adds, deletes, or modifies columns in a table, or deletes a table or data inside a table
TOPSpecifies the number of records to return in the result set
TRUNCATE TABLEDeletes the data inside a table, but not the table itself
UNIONCombines the result set of two or more SELECT statements (only distinct values)
UNION ALLCombines the result set of two or more SELECT statements (allows duplicate values)
UNIQUEA constraint that ensures that all values in a column are unique
UPDATEUpdates existing rows in a table
VALUESSpecifies the values of an INSERT INTO statement
VIEWCreates, updates, or deletes a view
WHEREFilters a result set to include only records that fulfill a specified condition
This post is licensed under CC BY 4.0 by the author.

Trending Tags