# SQL通用语法

  1. SQL语句可以单行或者多行书写,以分号结尾。
  2. SQL语句可以使用空格/缩进来增强语句的可读性。
  3. MySQL数据库的SQL语句不区分大小写,关键字可以使用大写。

# SQL分类

分类 全称 说明
DDL Data Definition Language 数据定义语言,用来定义数据库对象(数据库,表,字段)
DML Data Manipulation Language 数据操作语言,用来对数据库表中的数据进行增删改
DQL Data Query Language 数据查询语句,用来查询数据库中表的记录
DCL Data Control Language 数据控制语言,用来创建数据库用户、控制数据库的访问权限

# DDL

# 数据库的操作

  1. 查询
show databases; /* 查询所有数据库 */
selectt database(); /* 查询当前数据库 */
  1. 创建
create database [if no exists] database_name default charset utf8mb4;
  1. 删除
drop database [IF EXISTS] database_name;
  1. 使用
use database_name;

# 表操作

  1. 查询
show tables; /* 当前数据库所有表 */
desc table_name; /* 查询表结构 */
show create table table_name; /* 查询指定表的建表语句 */
  1. 创建
  • create table
create table table_name(
  filed_name file_type [comment file_comment],
  filed_name2 file_type2 [comment file_comment]
)[comment table_comment]
  1. 修改
  • alter table
-- 添加字段
 alter table table_name add filed_name 类型(长度) [comment 注释][ 约束];
 -- 修改数据类型
 alter table table_name modify 字段名 新数据类型(长度);
 -- 修改字段名和字段类型
 alter table table_name change 旧字段名 新字段名 类型(长度) [comment 注释] [约束];
 -- 修改表明
 alter table old_table_name rename to new_table_name;
  1. 删除
-- 删除表中某个字段
alter table table_name drop field_name;
-- 删除表
drop table [if exists] table_name;
-- 删除指定表,并重新创建该表
truncate table table_name;

# DML

  1. 添加数据
  • insert into ... values ...
-- 给指定字段添加数据
insert into table_name (字段1, 字段2...) values(1,2...);
-- 给全部字段添加数据 按照索引来添加
insert into table_name values(1,2...)
-- 批量添加数据
insert into table_name (字段1, 字段2, ...) values(1,2, ...), (1,2, ...), (1,2, ...);
insert into table_name values(1,2, ...),(1,2, ...);

2.修改数据

  • update
update table_name 字段1=1, 字段2=2,... [where 条件];
  1. 删除数据
  • delete from
-- 不加条件语句则删除所有数据
delete from table_name [where 条件]

# DQL

select
  字段列表
from
  表名称列表
where
  条件列表
group by
  分组字段列表
having
  分组后条件列表
order by
  排序字段列表
limit
  分页参数

# 1. 查询多个字段

select 字段1,字段2... from table_name;
-- 设置别名
select 字段1[ as 别名] from table_name;
-- 去除重复记录
select distinct 字段列表 from table_name;

# 2. 条件查询

select 字段列表 from table_name where 条件列表;
  • 条件
比较运算法 功能
> 大于
>= 大于等于
< 小于
<= 小于等于
= 等于
!= 不等于
between ... and ... 在范围之内的
in(值1,值2...) 在 in 之后的列表中的值, 多选一
like 模糊匹配(_匹配单个字符,%匹配任意一个字符)(__, %test%)
is null 是 null
  • 逻辑运算符
逻辑运算符 功能
and 或 &&
or 或 ||
not 或 !

# 3. 聚合函数

  • 将一列数据作为一个整体,进行纵向计算
函数 功能
count 统计数据数量。total
max 最大值
min 最小值
avg 平均值
sum 求和
select count(*) from test;

# 4. 分组查询

  • group by: 根据字段分组 查数据
  • having: 分组之后根据条件再过滤一遍
  • 一般分组查询的都是 分组的字段 + 聚合函数
select 字段列表 from table_name [where 条件] group by 分组字段名 [having 分组后过滤条件];
-- 获取年龄小于45,并更具地址分组,获取数量大于3的地址
select address, count(*) from test where age < 45 group by address having count(*) > 3

# 5. 排序查询

  • asc: 升序(默认,可省略)
  • desc: 倒序
select 字段列表 from table_name order by 字段1 排序方式1, 字段2 排序方式2;

# 6. 分页查询

  • 从 起始索引 开始 查 多少条数据
select * from table_name limit 起始索引,查询记录数;