以下是MySQL常用的语法汇总:
- 创建数据库
CREATE DATABASE database_name; - 删除数据库
DROP DATABASE database_name; - 创建表
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
…
); - 删除表
DROP TABLE table_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 column1, column2, … FROM table_name ORDER BY column1 ASC/DESC;
- 分组
SELECT column1, SUM(column2) FROM table_name GROUP BY column1;
- 连接
SELECT column1, column2, … FROM table_name1 JOIN table_name2 ON condition;
- 子查询
SELECT column1 FROM table_name WHERE column2 = (SELECT column3 FROM table_name2 WHERE condition);
- 聚合函数
SELECT COUNT(column1), SUM(column2), AVG(column3), MAX(column4), MIN(column5) FROM table_name;
- 数据类型
INT, BIGINT, FLOAT, DOUBLE, CHAR, VARCHAR, TEXT, DATE, TIME, DATETIME, TIMESTAMP
- 约束
PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK
- 创建索引
CREATE INDEX index_name ON table_name (column1, column2, …);
- 删除索引
DROP INDEX index_name ON table_name;
- 外键约束
ALTER TABLE table_name ADD FOREIGN KEY (column1) REFERENCES table_name2(column2);
- 修改表
ALTER TABLE table_name ADD column_name datatype;
- 删除列
ALTER TABLE table_name DROP column_name;
- 修改列
ALTER TABLE table_name MODIFY column_name datatype;
- 添加约束
ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, …);
- 删除约束
ALTER TABLE table_name DROP CONSTRAINT constraint_name;
- 视图
CREATE VIEW view_name AS SELECT column1, column2, … FROM table_name WHERE condition;
- 存储过程
CREATE PROCEDURE procedure_name (IN param1 datatype1, OUT param2 datatype2) BEGIN SELECT column1, column2, … FROM table_name WHERE condition; END;
- 触发器
CREATE TRIGGER trigger_name BEFORE/AFTER INSERT/UPDATE/DELETE ON table_name FOR EACH ROW BEGIN … END;
- 用户管理
CREATE USER user_name@localhost IDENTIFIED BY ‘password’;
- 授权
GRANT SELECT, INSERT, UPDATE, DELETE ON database_name.table_name TO user_name@localhost;
- 撤销授权
REVOKE SELECT, INSERT, UPDATE, DELETE ON database_name.table_name FROM user_name@localhost;
- 导入数据
LOAD DATA INFILE ‘file_name’ INTO TABLE table_name;
- 导出数据
SELECT column1, column2, … INTO OUTFILE ‘file_name’ FROM table_name;