深入解析:MySQL——增删改查操作

一、数据库的增删改查

语句中的'[]'是可选项,'{}'是必修项,'|'表示只能选择其中一项。

1.增加操作
create database [if not exists] 数据库名 [[default] character set 字符集] [collate 排序规则] ;

2.删除操作
drop database [if exists] 数据库名;

3.选择操作
use 数据库名;

4.查询操作

  • 查看所有数据库:show databases;
  • 查看数据库创建信息:show create datadase 数据库名;
  • 查看当前数据库:select database();

二、数据表的增删改查

1.增加操作
create table 表名(
字段1 类型[comment 注释],
字段2 类型[comment 注释]...
) [comment 注释];

2.删除操作
drop table [if exists] 表名;

3.修改操作
增加字段:alter table 表名 add 字段名 类型;
修改类型:alter table 表名 modify 字段名 新类型;
修改字段:alter table 表名 change 旧字段 新字段 新类型;
删除字段:alter table 表名 drop 字段名;
重新命名:alter table 表名 remane to 新表名;

4.查询操作
查看所有表:show tabels;
查看表结构:desc/describe table 表名;
查看建表语句:show create table 表名;

三、表格数据的增删改查

1.增加操作
insert into 表名 (字段1,字段2...) values(值1,值2...),(值1,值2...)...;
当给表格所有字段赋值时,字段部分可省去,即insert into 表名 values(值1,值2...),(值1,值2...)...;

2.删除操作
delect table 表名 [where 条件];

3.修改操作
update 表名 set 字段1=值1,字段2=值2..[where 条件];

4.查询操作

select 字段列表 from 表名列表
[where 条件列表] [group by 分组字段] [having 条件列表] [order by 字段列表] [limit 分页参数];

(1)基本查询

  • 查询多个字段:select 字段1,字段2... from 表名;
  • 查询所有字段:select * from 表名;
  • 设置字段别名:select 字段1 [[as] 别名1],字段2 [[as] 别名2]... from 表名;
  • 去除重复记录:select distinct 字段 from 表名;

(2)条件查询:select 字段列表 from 表名列表 where 条件列表;

  • 比较条件
    • >,>=,<,<=,=,<>或!=
    • between...and...(含最大值最小值)
    • in
    • like 占位符(%占多个字符,_占一个字符)
    • is null
  • 逻辑条件
    • and或&&
    • or或||
    • not或!

(3)聚合函数(null不参与聚合函数计算):select 聚合函数(字段) from 表名列表;

  • 统计数量:count(count(*)表示统计总数量)
  • 求最大值:max
  • 求最小值:min
  • 求平均值:avg
  • 求和:sum

(4)分组查询:select 字段列表 from 表名列表 group by 分组字段 [having 条件列表] ;

  • where不能对聚合函数进行判断,而having能够

(5)排序查询:select 字段列表 from 表名列表 order by 字段1 方式1,字段2 方式2...;

  • 升序:asc(默认,可省略不写)
  • 降序:desc
  • 若是是多字段排序,当第一个字段相同时,才会根据第二个字段排序

(6)分页查询:

  • 从起始索引开始查询几条资料:select 字段列表 from 表名列表 limit 起始索引,查询记录数;
    • eg:select x from x limit 3,4;表示查询第4-7条记录(不包括起始索引)
  • 跳过几条数据后查询几条数据:select 字段列表 from 表名列表 limit 查询记录数 offset 偏移量;
    • eg:select x from x limit 3 offset 5;表示查询第6-8条记录(跳过前5个后的3条记录)

posted on 2026-02-05 09:10  ljbguanli  阅读(0)  评论(0)    收藏  举报