题目描述
(通过次数43,086 | 提交次数55,609,通过率77.48%)
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/problems/actors-and-directors-who-cooperated-at-least-three-times
//测试数据 Create table If Not Exists ActorDirector (actor_id int, director_id int, timestamp int); insert into ActorDirector (actor_id, director_id, timestamp) values ('1', '1', '0'); insert into ActorDirector (actor_id, director_id, timestamp) values ('1', '1', '1'); insert into ActorDirector (actor_id, director_id, timestamp) values ('1', '1', '2'); insert into ActorDirector (actor_id, director_id, timestamp) values ('1', '2', '3'); insert into ActorDirector (actor_id, director_id, timestamp) values ('1', '2', '4'); insert into ActorDirector (actor_id, director_id, timestamp) values ('2', '1', '5'); insert into ActorDirector (actor_id, director_id, timestamp) values ('2', '1', '6');
解题思路
ActorDirector表保存了演员和导演每次的合作记录。
题目要求:返回合作了三次及以上的演员和导演。
根据ActorDirector表中的数据,可以先汇总统计出每个演员和导演合作的次数。使用GROUP BY+COUNT可以实现。
然后,再筛选出合作次数在三次及以下的记录即可。使用HAVING子句可以从汇总后的结果中筛选出需要的数据。
参考SQL
未特别说明的情况下,参考SQL为基于MySQL8.0实现。
select actor_id,director_id from ActorDirector group by actor_id,director_id having count(1)>=3;
本站所有内容均为原创,本站保留所有权利。仅允许非商业用途的转载,但必须注明来源网站、作者、来源链接!否则,由此造成的一切后果,由转载方承担!
干货分享、技术提升、面试笔试、学习交流,欢迎关注公众号:xuesql。QQ学习交流群:209942678。