SQL
介绍
SQL(Structured Query Language)是用于管理(如检索、插入、更新和删除)关系数据库中的数据的标准编程语言。
分类
- 数据定义语言-DDL
- 数据操作语言-DML
- 数据查询语言-DQL
- 数据控制语言-DCL
数据定义语言(DDL – Data Definition Language)
创建表
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
...
);
删除表
DROP TABLE table_name;
修改表
- 添加列
ALTER TABLE table_name ADD column_name datatype;
- 删除列
ALTER TABLE table_name DROP COLUMN column_name;
- 修改列
ALTER TABLE table_name MODIFY COLUMN column_name new_datatype;
- 重命名列(MySQL中没有直接的ALTER命令来重命名列,但可以使用
CHANGE
)
ALTER TABLE table_name CHANGE old_column_name new_column_name datatype;
数据操作语言(DML – Data Manipulation Language)
插入数据
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;
数据查询语言(DQL – Data Query Language)
查询数据
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_name [ASC|DESC]
LIMIT number;
SELECT
:选择需要显示的列FROM
:指定数据来源的表WHERE
:设置过滤条件ORDER BY
:对结果集进行排序LIMIT
:限制返回的记录数
连接表
- 内连接(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;
数据控制语言(DCL – Data Control Language)
授予权限
GRANT permission_type ON database_name.table_name TO 'username'@'host';
撤销权限
REVOKE permission_type ON database_name.table_name FROM 'username'@'host';
其他常用SQL命令
- 创建索引
CREATE INDEX index_name ON table_name (column_name);
- 删除索引
DROP INDEX index_name ON table_name;
- 创建视图
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
- 删除视图
DROP VIEW view_name;