SQL(Structured Query Language)是一种用于存储、操作和检索数据库中数据的标准编程语言。以下是一些常用的 SQL 语法:
-
数据库操作
- 创建数据库:
CREATE DATABASE database_name;
- 删除数据库:
DROP DATABASE database_name;
- 选择数据库:
USE database_name;
- 创建数据库:
-
表操作
- 创建表:
CREATE TABLE table_name (column1 datatype, column2 datatype, ...);
- 删除表:
DROP TABLE table_name;
- 修改表结构:
ALTER TABLE table_name ADD column_name datatype;
- 删除表中的列:
ALTER TABLE table_name DROP COLUMN column_name;
- 创建表:
-
数据操作
- 插入数据:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
- 更新数据:
UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;
- 删除数据:
DELETE FROM table_name WHERE condition;
- 查询数据:
SELECT column1, column2, ... FROM table_name WHERE condition;
- 插入数据:
-
条件查询
- 等于:
SELECT * FROM table_name WHERE column = value;
- 不等于:
SELECT * FROM table_name WHERE column != value;
- 大于:
SELECT * FROM table_name WHERE column > value;
- 大于等于:
SELECT * FROM table_name WHERE column >= value;
- 小于:
SELECT * FROM table_name WHERE column < value;
- 小于等于:
SELECT * FROM table_name WHERE column <= value;
- BETWEEN:
SELECT * FROM table_name WHERE column BETWEEN value1 AND value2;
- LIKE(模糊查询):
SELECT * FROM table_name WHERE column LIKE 'value%';
- IN:
SELECT * FROM table_name WHERE column IN (value1, value2, ...);
- AND/OR:
SELECT * FROM table_name WHERE column1 = value1 AND column2 = value2;
- 等于:
-
聚合函数
- COUNT:
SELECT COUNT(*) FROM table_name;
- SUM:
SELECT SUM(column) FROM table_name;
- AVG:
SELECT AVG(column) FROM table_name;
- MAX:
SELECT MAX(column) FROM table_name;
- MIN:
SELECT MIN(column) FROM table_name;
- COUNT:
-
分组和排序
- 分组:
SELECT column1, COUNT(*) FROM table_name GROUP BY column1;
- 排序:
SELECT * FROM table_name ORDER BY column1 ASC, column2 DESC;
- 分组:
-
连接查询
- 内连接(INNER JOIN):
SELECT * FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;
- 左连接(LEFT JOIN):
SELECT * FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
- 右连接(RIGHT JOIN):
SELECT * FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;
- 全连接(FULL JOIN)(注意:并非所有数据库系统都支持 FULL JOIN):
SELECT * FROM table1 FULL JOIN table2 ON table1.column_name = table2.column_name;
- 内连接(INNER JOIN):
-
子查询
- 嵌套查询:
SELECT * FROM table_name WHERE column IN (SELECT column FROM other_table WHERE condition);
- 嵌套查询:
-
事务控制
- 开启事务:
BEGIN TRANSACTION;
- 提交事务:
COMMIT;
- 回滚事务:
ROLLBACK;
- 开启事务:
-
权限控制
- 授予权限:
GRANT SELECT, INSERT ON table_name TO user_name;
- 撤销权限:
REVOKE SELECT, INSERT ON table_name FROM user_name;
- 授予权限: