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 次。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/actors-and-directors-who-cooperated-at-least-three-times
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
审题:根据ActorDirector表查询至少合作过三次的演员。
思考:按照ActorDirector表中导演和演员关系分组,相同的三次以上就是结果。如何分组?
解题:
找出一起至少合作过3次的演员和导演。
对二元组(演员,导演)分组,计算每组个数,选出每组个数>=3的行。
应用group by和count。
select A.actor_id,A.director_id
from ActorDirector as A
group by A.actor_id,A.director_id
having count(A.timestamp) >= 3
-- 练习
select A.actor_id,A.director_id from actorDirector as A
group by A.actor_id , A.director_id having count(A.timestamp) >=3;
知识点:
分组,排序,选择