mysql最基本使用命令(关于表)
1. 创建表
create table info(id int auto_increment, name char(32) not null, age int not null, registerdate date not null, primary key (id));
解析:
auto_increment 属性用于创建自增字段
not null 设置字段不能为空
registerdate 默认会记录创建记录时的当前日期和时间
primary key 定义了表的主键,确保 id 值的唯一性
2.查看数据库所有表
show tables;
3.查看表结构
desc 表名;
desc info;
4.插入字段
insert into 表名 (name,age,registerdate) values("zhangsan",18,"2024-10-26");
insert into info (name,age,registerdate) values("zhangsan",18,"2024-10-26");
5.查看表内容
select 字段名 from 表名;
select * from info;
增删改查部分
1. 查
① where 筛选条件
select 字段名 from 表名 [where 筛选条件] [offset 数据偏移量] [limit 设定返回记录数]
筛选条件操作符: = <> != > < >= <= like
#只查三行数据
select * from info limit 3;
#从表的第二行开始查(往后偏移1行),只查两行数据,
select * from info limit 2 offset 1;
# 只差id大于3,并且age等于18的数据
select * from info where id >2 and age=18;
#筛选2024年10月的数据(like 模糊查询)
select * from info where registerdate like "2024-10-%";
② order by 排序
正序
select 列名 from 表名 order by 通过某列数据排序;
select * from info order by id;
反序
select 列名 from 表名 order by 通过某列数据排序 desc;
select * from info order by id desc;
③ group by 分组
select 字段名 from 表名 group by 字段名;
select * from info group by name;
④ count() 统计
分组统计
select *,count(*) from 表名 group by 字段名;
select *,count(*) from info group by name;
⑤ as 起别名
select *,count(*) as 别名 from 表名 group by 字段名;
select *,count(*) as sum from info group by name;
⑥ sum 求和
# 分组求和
select *,sum(age) as sum from info group by name;
# 分组求和,和所有和(with rollup)
select coalesce(name,"Total Age"),sum(age) as sum from info group by name with rollup;
2.改
update 表名 set 修改后的字段内容 where 条件;
update info set name="zhang",age=20 where id=1;
3.删
delete from 表名 where 条件;
delete from info where name="zhang";
4.增
insert into 表名 (字段) values(内容);
insert into info (name,age,registerdate) values("liuliu",18,"2024-10-26");
字段的增删改
1. 字段的增
alter table 表名 add 字段名 字段类型;
alter table info add sex enum("M","F"); # ENUM 数据类型,只允许存储枚举类型中的值
2. 字段的删
alter table 表名 drop 字段名;
alter table info drop age;
3. 字段的改
# 修改字段类型
alter table 表名 modify 字段名 新字段类型;
alter table info modify sex enum("F","M") not null;
# 修改字段名
alter table 表名 change 字段名 新字段名 新字段类型;
alter table info change sex gender char(32) not null default "NULL";
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话