602. 好友申请 II :谁有最多的好友(力扣mysql题,难度:中等)

RequestAccepted 表:

+----------------+---------+

| Column Name | Type |

+----------------+---------+

| requester_id | int |

| accepter_id | int |

| accept_date | date |

+----------------+---------+

(requester_id, accepter_id) 是这张表的主键(具有唯一值的列的组合)。 这张表包含发送好友请求的人的 ID ,接收好友请求的人的 ID ,以及好友请求通过的日期。

要求:编写解决方案,找出拥有最多的好友的人和他拥有的好友数目。

注:生成的测试用例保证拥有最多好友数目的只有 1 个人。

查询结果格式如下例所示。

示例 : 输入: RequestAccepted 表:

+--------------+-------------+-------------+

| requester_id | accepter_id | accept_date |

+--------------+-------------+-------------+

| 1 | 2 | 2016/06/03 |

| 1 | 3 | 2016/06/08 |

| 2 | 3 | 2016/06/08 |

| 3 | 4 | 2016/06/09 |

+--------------+-------------+-------------+

输出:

+----+-----+

| id | num |

+----+-----+

| 3 | 3 |

+----+-----+

解释:编号为 3 的人是编号为 1 ,2 和 4 的人的好友,所以他总共有 3 个好友,比其他人都多。

解题分析: 主动加好友和被动加好友,都是自己的好友,需要查出所有好友;在根据好友数量来得出结论.

解题代码

with tb as (select t.requester_id id, count(1) num

from (select requester_id

from requestaccepted

union all

select accepter_id

from requestaccepted) t

group by t.requester_id)

select tb.id, tb.num from tb where tb.num = (select max(tb.num) from tb);

#select tb.id, tb.num from tb order by tb.num desc limit 1;

#可和elect tb.id, tb.num from tb where tb.num = (select max(tb.num) from tb)替换;

//输出结果

/*

+----+-----+

| id | num |

+----+-----+

| 3 | 3 |

+----+-----+

*/

代码分析 1.union all 和 union 的区别

union: 对两个结果集进行并集操作, 不包括重复行,相当于distinct, 同时进行默认规则的排序;

union all: 对两个结果集进行并集操作, 包括重复行, 即所有的结果全部显示, 不管是不是重复,不会排序;

#union all只是合并查询结果,并不会进行去重和排序操作,在没有去重的前提下,使用union all的执行效率要比union高

//例子:union all

select requester_id from requestaccepted union all select accepter_id from requestaccepted;

//输出:

/*

| requester_id |

| ------------ |

| 1 |

| 1 |

| 2 |

| 3 |

| 2 |

| 3 |

| 3 |

| 4 |

*/

//例子:union

select requester_id from requestaccepted union select accepter_id from requestaccepted;

//输出:

/*

| requester_id |

| ------------ |

| 1 |

| 2 |

| 3 |

| 4 |

*/

2.select tb.id, tb.num from tb where tb.num = (select max(tb.num) from tb);和select tb.id, tb.num from tb order by tb.num desc limit 1; 都可以

select tb.id, tb.num from tb where tb.num = (select max(tb.num) from tb);

//采用了mysql的max()函数,输出tb临时表中num最大的数据,在where查询出来.

select tb.id, tb.num from tb order by tb.num desc limit 1;

//直接order by num desc 倒序取第一条,就是结果

注意:with tb as 在mysql8.0后才可用,with tb as (select * from stadium ) 后面要和 select 联用,不能单独使用with tb as

参考文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: