mysql命令合集(二)
自连接
自己的表和自己的表连接,核心:一张表拆为两张一样的表即可
- 准备工作,创建一个数据表并且插入模拟数据
create table `category` (
`categoryid` int(10) unsigned not null auto_increment comment '主题id',
`pid` int(10) not null comment '父id',
`categoryName` varchar(50) not null comment '主题名字',
primary key (`categoryid`)
) engine=innodb auto_increment=9 default charset=utf8
insert into `category` (`categoryid`,`pid`, `categoryName`)
values('2','1','信息技术'),
('3','1','软件开发'),
('4','3','数据库'),
('5','1','美术设计'),
('6','3','web开发'),
('7','5','ps技术'),
('8','2','办公信息');
效果图

- 拆表
- 父类
| cotegoryid | categoryName |
|---|---|
| 2 | 信息技术 |
| 3 | 软件开发 |
| 5 | 美术设计 |
- 子类
| pid | cotegoryid | categoryName |
|---|---|---|
| 3 | 4 | 数据库 |
| 2 | 8 | 办公信息 |
| 3 | 6 | web开发 |
| 5 | 7 | 美术设计 |
- 期望结果:查询父类对应的子类关系
| 父类 | 子类 |
|---|---|
| 信息技术 | 办公信息 |
| 软件开发 | 数据库 |
| 软件开发 | web开发 |
| 美术设计 | ps技术 |
- 操作
# 使用连接查询的方式
select a.`categoryName` as '父级',b.`categoryName` as '子级'
from `category` as a
inner join `category` as b
on a.`categoryid`=b.`pid`

-- 使用等值查询的方式
select a.`categoryName` as '父类',b.`categoryName` as '子类'
from `category` as a,`category` as b
where a.`categoryid`=b.`pid`

分页和排序
- 排序order by
- 排序:升序asc,降序desc
- 语法:select * from students order by studentNo desc
- 分页:limit
- 为啥要分页?缓解数据库压力
- 瀑布流:给人体验更好,不分页进行数据加载
- 分页语法:
select <列名> from <表名> limit <起始值>,<步长> -- limit 这个语法的意思就是当前表从哪一行开始,向后移动多少 -- 其中起始值和步长可以为一个值 select * from students limit 5 -- 代表查询学生表的数据的前五条 - limit和order by一起使用
-- 语法
select <列名> from <表名> order by <期望排序列> [asc|desc] limit <起始值>,<步长值>
-- 举例
select * from students order by studentNo desc limit 1,5
子查询和嵌套查询
- 子查询
- 语法:
-- 子查询方式是由里即外的方式,先运行where 后面括号中的,然后再运行括号外面的 select <列名> from <表名> where <字段名>=(select ... )- 查询 数据库结构-1 的所有考试结果(学号,科目编号,成绩),降序排序
- 方式一:使用连接查询
select `studentNo`,r.`subjectNo`,`studentResult` from `result` r inner join `subject` sub on r.subjectNo = sub.subjectNo where subjectName='数据库结构-1' order by studentResult desc- 方式二:使用子查询
select `studentNo`,`subjectNo`,`studentResult` from `result` where subjectNo=( select subjectNo from `subject` where subjectName='数据库结构-1' ) order by studentResult desc
select 查询语法



浙公网安备 33010602011771号