MySQL之复杂查询的实现

目录
  • 1.排序
  • 2.分组
  • 3.联合查询
  • 4.多表连接

1.排序

order by 子句来设定哪个字段哪种方式来进行排序,再返回搜索结果。
desc:降序

select * from blog order by balance desc;

asc:升序,默认,可不写

select * from blog order by balance asc;

多字段排序

update blog set age = 25 where age < 25;

先根据年龄升序,再根据余额降序

select * from blog order by age asc, balance desc;

2.分组

group by 语句根据一个或多个列对结果集进行分组。
新建员工表

create table `employee` (
  `id` int not null,
  `name` varchar(20) not null default '',
  `identity` varchar(20) not null default '',
  `signin` tinyint not null default '0' comment '打卡次数',
  `date` date not null,
  primary key (`id`)
) engine=innodb;

插入数据

insert into `employee` values 
('1', '小明', 'firemen', 3, '2022-02-21'), 
('2', '小王', 'doctor', 3, '2022-02-21'), 
('3', '小丽', 'police', 3, '2022-02-21'), 
('4', '小王', 'doctor', 2, '2022-02-22'), 
('5', '小明', 'firemen', 1, '2022-02-22'), 
('6', '小丽', 'police', 3, '2022-02-22'), 
('7', '小明', 'firemen', 2, '2022-02-23'),
('8', '小王', 'doctor', 2, '2022-02-23'),
('9', '小红', 'nurse', 3, '2022-02-23');

统计每人打卡记录数

select name, count(*) from employee group by name;

with rollup 可以实现在分组统计数据基础上再进行相同的统计(sum,avg,count…)
统计每人打卡总数

select name, sum(signin) as signin_count from employee group by name with rollup;

其中记录 null 表示所有人的登录次数。
使用 coalesce 来设置一个可以取代 null 的名称
coalesce 语法:select coalesce(a,b,c);

select name, sum(signin) as signin_count from employee group by name with rollup;

3.联合查询

union 操作符用于连接两个以上的 select 语句的结果组合到一个结果集合中。
union all:返回所有结果集,包含重复数据。

select author from blog 
union all 
select identity from employee;

报错:illegal mix of collations for operation ‘union’
原因:相同字段的编码不一致造成的

解决:修改blog表的author字段

alter table blog modify `author` varchar(40) collate utf8mb4_general_ci not null default '';

union distinct: 删除结果集中重复的数据。默认,可不写

select author from blog 
union
select identity from employee;

4.多表连接

inner join(内连接,或等值连接):获取两个表中字段匹配关系的记录。
left join(左连接):获取左表所有记录,即使右表没有对应匹配的记录。
right join(右连接): 与 left join 相反,用于获取右表所有记录,即使左表没有对应匹配的记录。

内连接
inner 可以省略

select b.author, b.age, b.title, e.name, e.signin from blog b 
inner join employee e on b.author = e.identity;

where条件实现内连接效果

select b.author, b.age, b.title, e.name, e.signin from blog b,employee e 
where b.author = e.identity;

左连接:读取左边数据表的全部数据,即便右边表无对应数据。

select b.author, b.age, b.title, e.name, e.signin from blog b 
left join employee e on b.author = e.identity;

右连接:读取右边数据表的全部数据,即便左边边表无对应数据。

select b.author, b.age, b.title, e.name, e.signin from blog b 
right join employee e on b.author = e.identity;

 到此这篇关于mysql之复杂查询的实现的文章就介绍到这了,更多相关mysql 复杂查询内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐