MySQL数据操作总结

创建数据库

create database if not exists demodb;

查看数据库

show databases;

使用数据库

use demodb;

创建表

create table stu(
	id int unsigned not null auto_increment primary key,
	name varchar(16) not null unique,
	age tinyint unsigned not null default 20,
	sex enum('w','m') not null default 'm',
	classid char(8)
);

查看表结构

desc stu

查看建表语句

show create table stu\G

查看当前库下的所有表

show tables;

数据的添加

# 指定字段的方式
insert into stu(id, name, age, sex, classid) values(1, 'lili', 22, 'w', 'pythonx-1');
# 不指定字段的方式,一定按照表结构的顺序, 自增的id可以是空
insert into stu values(null, 'lili', 22, 'w', 'pythonx-1');
# 只指定部分字段,其他字段默认或自增
insert into stu(name, classid) values('jack', 'pythonx-2');
# 批量添加数据
insert into stu(name, classid) values('jack', 'pythonx-3'), ('nn01','pythonx-4'), ('nn02','pythonx-5'), ('nn03','pythonx-6')

数据的修改

# 修改stu表中的数据 id为2、5、6的
update stu set age=21, sex='w' where id in(2,5,6)
# 修改一个不存在的数据并不会报错
update stu set age=23, sex='m' where id=100;

数据的删除

# 删除不存在的数据不会报错,删除id为100和200的数据
delete from stu where id in(100, 200);
# 删除 id>100的数据
delete from stu where id>100;
# 删除在100和200之间的数据,包括两端的数据
delete from stu where id between 100 and 200;

数据的查询(最重要)

# 查询所有数据
select * from stu;
# 查询多个字段,注意逗号(英文状态下)分隔
select id, name from stu;
# 查询字段中添加字段并做运算
select id, name, age, age+5 from stu;
# 查询字段并使用别名, 通过as关键字
select id, name as username, age, age+5 as age5 from stu;
# 查询字段并使用别名,  as关键字省略不写
select id, name username, age, age+5 age5 from stu;
# 查询表中所有字段数据
select * from stu;
# 整理注意,数据在select输出的时候,和表结构不一定一致, 这里追加字段
select *, 'hangzhou' as city from stu; # 此时查到所有数据并且在最后一列加上值为hangzhou的city字段
# 查询表中所有字段的部分数据
select * from stu where id=2;
select * from stu where id<5;
select * from stu where id in(2,3,4);
select * from stu where id between 3 and 9;
select * from stu where id not between 8 and 9;
select * from stu where id >=10 and age <=100;
select * from stu where id >=10 or age <=100;
# 查询某个库(demodb)下的某张表(demotab)
select * from demodb.demotab where createtime is null;
# 模糊查询
select * from stu where name like "%a%" # 包含式查询 中间含有a的

未完成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wang's Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值