数据库每日一题---第11天:合作过至少三次的演员和导演

202 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第16天,点击查看活动详情

一、问题描述

ActorDirector 表:

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| actor_id    | int     |
| director_id | int     |
| timestamp   | int     |
+-------------+---------+
timestamp 是这张表的主键.

写一条SQL查询语句获取合作过至少三次的演员和导演的 id 对 (actor_id, director_id),输出样例如下面所示

题目链接:合作过至少三次的演员和导演

二、题目要求

样例

ActorDirector 表:
+-------------+-------------+-------------+
| actor_id    | director_id | timestamp   |
+-------------+-------------+-------------+
| 1           | 1           | 0           |
| 1           | 1           | 1           |
| 1           | 1           | 2           |
| 1           | 2           | 3           |
| 1           | 2           | 4           |
| 2           | 1           | 5           |
| 2           | 1           | 6           |
+-------------+-------------+-------------+

Result 表:
+-------------+-------------+
| actor_id    | director_id |
+-------------+-------------+
| 1           | 1           |
+-------------+-------------+
唯一的 id 对是 (1, 1),他们恰好合作了 3 次。

考察

1.聚合函数
2.建议用时10~25min

三、问题分析

这一题题目的要求是求出至少出现合作三次的演员与导演,我们很自然的就会想到聚合函数分组判断,不然你一行一行筛选太费事,并且不划算。那么什么叫聚合函数

group by语句从英文的字面意义上理解就是根据(by)一定的规则进行分组(Group)作用:通过一定的规则将一个数据集划分成若干个小的区域,然后针对若干个小区域进行数据处理。

having就是对于使用group by语句分组之后的结果,进一步筛选,缩小范围,求出结果。

以这一题举例,我们先通过下面的代码,对actor_id 和 director_id 分类的结果如下:

select actor_id, director_id,count(*) as 'number'
from   ActorDirector
group by actor_id, director_id


{"headers": ["actor_id", "director_id", "number"], 
"values": [ [1, 1, 3], 
            [2, 1, 2], 
            [1, 2, 2]]}

明显只有第一行符号题目的要求,所以我们通过having count(*)>=3对分组之后的结果,再次筛选,最后只有第一行符合要求,我们就输出第一行就行了。

四、编码实现

select actor_id, director_id
from   ActorDirector
group by actor_id, director_id
having count(*)>=3

五、测试结果

1.png

2.png

19.png