目录
- 1 题目
- 2 建表语句
- 3 题解
题目来源:腾讯。
1 题目
有两个表,朋友关系表user_friend
,用户步数表user_steps
。朋友关系表包含两个字段,用户id,用户好友的id;用户步数表包含两个字段,用户id,用户的步数
查询:占据多少个好友的封面(在好友的列表中排行第一,且必须超过好友的步数)
朋友关系表user_friend
+----------+------------+
| user_id | friend_id |
+----------+------------+
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 3 |
| 2 | 4 |
| 2 | 5 |
| 3 | 1 |
| 3 | 4 |
| 3 | 5 |
| 4 | 2 |
| 4 | 3 |
| 4 | 5 |
| 5 | 2 |
| 5 | 3 |
| 5 | 4 |
+----------+------------+
用户步数表user_steps
+---------------------+-------------------+
| user_steps.user_id | user_steps.steps |
+---------------------+-------------------+
| 1 | 100 |
| 2 | 95 |
| 3 | 90 |
| 4 | 80 |
| 5 | 10 |
+---------------------+-------------------+
2 建表语句
-- 创建好友关系表
CREATE TABLE user_friend
(
user_id INT,
friend_id INT
) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';
-- 插入数据
INSERT INTO user_friend
VALUES (1, 2),
(1, 3),
(2, 1),
(2, 3),
(2, 4),
(2, 5),
(3, 1),
(3, 4),
(3, 5),
(4, 2),
(4, 3),
(4, 5),
(5, 2),
(5, 3),
(5, 4);
CREATE TABLE user_steps
(
user_id INT,
steps INT
) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';
INSERT INTO user_steps
VALUES (1, 100),
(2, 95),
(3, 90),
(4, 80),
(5, 10);
3 题解
步骤一:获取自己的步数和好友的步数
select u1.user_id,
u2.steps as user_steps,
friend_id,
u3.steps as friend_steps
from
user_friend u1
left join
user_steps u2
on u1.user_id=u2.user_id
left join
user_steps u3
on u1.friend_id=u3.user_id
执行结果
步骤二:取出自己步数比好友步数多的记录。
select
user_id,
user_steps,
friend_id,
friend_steps
from
(select u1.user_id,
u2.steps as user_steps,
friend_id,
u3.steps as friend_steps
from
user_friend u1
left join
user_steps u2
on u1.user_id=u2.user_id
left join
user_steps u3
on u1.friend_id=u3.user_id)t
where user_steps>friend_steps;
执行结果
步骤三:按照 friend_id 进行分组排序,取出步数第一名的用户好友记录。
select
user_id,
user_steps,
friend_id,
friend_steps
from
(select
user_id,
user_steps,
friend_id,
friend_steps,
row_number() over (partition by friend_id order by user_steps desc) rn
from
(select u1.user_id,
u2.steps as user_steps,
friend_id,
u3.steps as friend_steps
from
user_friend u1
left join
user_steps u2
on u1.user_id=u2.user_id
left join
user_steps u3
on u1.friend_id=u3.user_id)t
where user_steps>friend_steps)tt
where rn=1;
执行结果
步骤四:关联用户好友表,计算占据封面个数。
select
ttt1.user_id,
count(user_steps) as fm_cnt
from
user_friend ttt1
left join
(select
user_id,
user_steps,
friend_id,
friend_steps
from
(select
user_id,
user_steps,
friend_id,
friend_steps,
row_number() over (partition by friend_id order by user_steps desc) rn
from
(select u1.user_id,
u2.steps as user_steps,
friend_id,
u3.steps as friend_steps
from
user_friend u1
left join
user_steps u2
on u1.user_id=u2.user_id
left join
user_steps u3
on u1.friend_id=u3.user_id)t
where user_steps>friend_steps)tt
where rn=1)ttt
on ttt1.user_id=ttt.user_id and ttt1.friend_id=ttt.friend_id
group by ttt1.user_id;
执行结果