数据库操作
新增数据库
1
create Database tp5
查看数据库,查看将要创建的数据库是否存在
1 | SHOW tp5 |
- 选择数据库
1 | USE tp5 |
- 删除数据库
1 | DROP DATABASE tp5 |
表操作
创建表
1
2
3
4
5
6
7
8
9
10CREATE TABLE `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` varchar(40) NOT NULL COMMENT '用户名',
`headurl` varchar(100) DEFAULT NULL COMMENT '头像地址',
`tel` varchar(11) DEFAULT NULL COMMENT '电话',
`createtime` varchar(11) DEFAULT NULL COMMENT '注册时间',
`password` varchar(40) DEFAULT NULL COMMENT '密码',
`age` int(3) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8mb4新增一条数据
1
2INSERT INTO `user` (`name`,`password`,`tel`,`age`)
VALUES ('数据','21232f297a57a5a743894a0e4a801fc3','18611488388','39');新增多条数据
1
2
3
4INSERT INTO `user` (`name`,`password`,`tel`,`age`)
VALUES ('胡鹏','21232f297a57a5a743894a0e4a801fc3','18842438941','23'),
('张新','21232f297a57a5a743894a0e4a801fc3','18842734041','22'),
('杨成','21232f297a57a5a743894a0e4a801fc3','18842437041','24');查询用户表中所有用户数据
1
SELECT * FROM `user`
查询user表中,所有用户的手机号
1
SELECT tel from `user`
查询用户id为5的用户数据
1
SELECT * from `user` WHERE id=5
查询年龄大于16的用户
1
SELECT * from user where age>16
查询年龄大于20小于40的用户
1
SELECT * from user where age>20 and age<40
查询年龄大于20小于40的前5个用户
1
SELECT * from user where age>20 and age<40 LIMIT 5
显示年龄最小的五个人
1
SELECT * from user where age>0 order by age asc limit 5
查询年龄大于20小于40的用户的名称
1
SELECT name from user where age>20 and age<40
所有用户按照age从小到大排序 desc降序 asc升序排序
1
SELECT * from user order by age desc
查询age为null的用户
1
SELECT * from user where age is NULL
查询年龄唯一的用户
1
SELECT DISTINCT age FROM `user`
多表查询
查询商品表中哪些用户购买过商品,并将用户信息显示出来
1
2
3SELECT user.id,user.name,order_goods.name
from user,order_goods
where order_goods.uid=user.id查询胡鹏买了哪些商品
1
2
3
4SELECT user.id as uid,user.name as username,order_goods.name as shopname,order_goods.id as oid
from user,order_goods
where order_goods.uid=user.id
and user.name='胡鹏'左连接
1
2
3SELECT * from user
left join order_goods
on user.id=order_goods.uid右连接
1
2
3SELECT * from user
right join order_goods
on user.id=order_goods.uid
子查询,用于子查询的关键字包括in、not in、=、!=、exists、not exists等
查询uid为 5,8,15,17的用户
1
2select * from user
where user.id in (5,8,15,17)查询购买过商品的用户信息
1
2SELECT * from user
where id in (select uid from order_goods)
使用 update 语句进行记录更新
名称为’数据’的用户改名为叶尚乐
1
UPDATE user SET name='叶尚乐' where name='数据'
将叶尚乐age修改为25,手机号码修改为17605087708
1
UPDATE user set age=25,tel=17605087708 where name='叶尚乐'
将id为20的用户age减一岁
1
update user set age=age-1 where id=20;
删除user表中年龄为空的用户
1
DELETE FROM user where age is NULL
删除id不为17的胡鹏用户
1
DELETE FROM user where id!=17 and name='胡鹏'
切记
- 删除时一定要记住加上where条件,不然会清空掉整个表的记录。
- 删除重要数据前一定要备份、备份、备份。