常用、实用 SQL 语句

内容纲要

一、数据操作语句(DML)

插入数据

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)

基本查询

SELECT column1, column2
FROM table_name;

带条件查询

SELECT column1, column2
FROM table_name
WHERE condition;

排序

SELECT column1, column2
FROM table_name
ORDER BY column1 ASC, column2 DESC;

分组

SELECT column1, COUNT(*)
FROM table_name
GROUP BY column1;

联合查询(JOIN)

内连接
SELECT a.column1, b.column2
FROM table1 a
INNER JOIN table2 b ON a.common_column = b.common_column;
左连接
SELECT a.column1, b.column2
FROM table1 a
LEFT JOIN table2 b ON a.common_column = b.common_column;
右连接
SELECT a.column1, b.column2
FROM table1 a
RIGHT JOIN table2 b ON a.common_column = b.common_column;

子查询

SELECT column1
FROM table_name
WHERE column2 = (SELECT column2 FROM another_table WHERE condition);

二、数据定义语句(DDL)

查询指定表的 DDL(数据定义语言)语句

SHOW CREATE TABLE your_table_name;

创建表

CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
    PRIMARY KEY (column1)
);

修改表

ALTER TABLE table_name
ADD column_name datatype;

ALTER TABLE table_name
DROP COLUMN column_name;

ALTER TABLE table_name
MODIFY COLUMN column_name datatype;

删除表

DROP TABLE table_name;

三、数据控制语句(DCL)

创建用户

CREATE USER 'username'@'host' IDENTIFIED BY 'password';

授权

GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'host';

撤销权限

REVOKE ALL PRIVILEGES ON database_name.* FROM 'username'@'host';

删除用户

DROP USER 'username'@'host';

四、实用函数

字符串操作

SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM table_name;

日期函数

SELECT NOW(); -- 当前日期和时间
SELECT CURDATE(); -- 当前日期
SELECT CURTIME(); -- 当前时间

数学函数

SELECT ROUND(column_name, 2) FROM table_name;
SELECT FLOOR(column_name) FROM table_name;
SELECT CEIL(column_name) FROM table_name;

Leave a Comment

您的电子邮箱地址不会被公开。 必填项已用*标注

close
arrow_upward