目录
- SQL 基本语法
- SQL 数据类型
- SQL 常用查询语句
- SQL 操作符
- SQL 约束
- SQL 索引和视图
- SQL 聚合函数
- SQL 日期和时间函数
- SQL 字符串函数
- SQL 示例查询
SQL 基本语法
- SELECT:查询数据
- INSERT INTO:插入数据
- UPDATE:更新数据
- DELETE:删除数据
- CREATE DATABASE:创建数据库
- CREATE TABLE:创建表
- ALTER TABLE:修改表
- DROP TABLE:删除表
- CREATE INDEX:创建索引
- DROP INDEX:删除索引
SQL 数据类型
- 数字类型:
INT
, FLOAT
, DOUBLE
, DECIMAL
- 字符类型:
CHAR
, VARCHAR
, TEXT
- 日期和时间类型:
DATE
, DATETIME
, TIMESTAMP
, TIME
- 布尔类型:
BOOLEAN
- 二进制类型:
BLOB
, BINARY
, VARBINARY
SQL 常用查询语句
SELECT 查询语句
SELECT column1, column2 FROM table_name;
WHERE 条件过滤
SELECT column1 FROM table_name WHERE condition;
ORDER BY 排序
SELECT column1 FROM table_name ORDER BY column1 ASC|DESC;
LIMIT 返回前 N 行
SELECT column1 FROM table_name LIMIT N;
SQL 操作符
- 逻辑运算符:
AND
, OR
, NOT
- 比较运算符:
=
, !=
, <
, >
, <=
, >=
, BETWEEN
, IN
, LIKE
- 集合操作符:
UNION
, INTERSECT
, EXCEPT
- NULL 判断:
IS NULL
, IS NOT NULL
- 字符串匹配:
LIKE
, REGEXP
SQL 约束
- NOT NULL:确保列不能包含 NULL 值
- UNIQUE:确保列的值唯一
- PRIMARY KEY:唯一标识记录
- FOREIGN KEY:建立表与表之间的关系
- CHECK:确保列中的值满足某种条件
- DEFAULT:为列设置默认值
SQL 索引和视图
CREATE INDEX index_name ON table_name(column_name);
CREATE VIEW view_name AS SELECT column1, column2 FROM table_name;
SQL 聚合函数
SELECT COUNT(column_name) FROM table_name;
SELECT SUM(column_name) FROM table_name;
SELECT AVG(column_name) FROM table_name;
SELECT MIN(column_name) FROM table_name;
SELECT MAX(column_name) FROM table_name;
SQL 日期和时间函数
SELECT DATE_ADD('2025-04-01', INTERVAL 1 DAY);
SELECT DATEDIFF('2025-04-02', '2025-04-01');
SQL 字符串函数
SELECT CONCAT(first_name, ' ', last_name) FROM employees;
SELECT LENGTH(column_name) FROM table_name;
SELECT UPPER(column_name) FROM table_name;
SELECT LOWER(column_name) FROM table_name;
SELECT SUBSTRING(column_name, 1, 3) FROM table_name;
SQL 示例查询
示例 1:查询所有员工的信息
示例 2:查询订单金额大于 100 的订单
SELECT * FROM orders WHERE amount > 100;
示例 3:计算每个部门的平均工资
SELECT department_id, AVG(salary) AS average_salary
FROM employees
GROUP BY department_id;
示例 4:插入新订单记录
INSERT INTO orders (order_date, customer_id, amount)
VALUES (NOW(), 1, 150.00);
示例 5:更新员工的薪资
UPDATE employees
SET salary = salary * 1.1
WHERE department_id = 2;
参考资料
发表回复