分享最近面试的sql面试题:
下面是表结构:
CREATE TABLE `video_records` (
`video_id` char(4) NOT NULL COMMENT '视频id',
`user_id` char(4) NOT NULL COMMENT '用户id',
`play_duration` int NOT NULL COMMENT '观看时长',
PRIMARY KEY (`video_id`,`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
示例数据:
insert into video_records value ("1001","A001",200)
insert into video_records value ("1001","B001",300)insert into video_records value ("1002","A001",488)
insert into video_records value ("1002","B001",270)
insert into video_records value ("1003","A001",234)
编写sql语句,要求:查找所有观看视频ID"1001"的观看时长大于视频ID“1002”的观看时长的用户ID
思路:
- 使用自连接(
JOIN
)将video_views
表自身连接起来,基于user_id
匹配相同的用户在观看不同视频的记录。WHERE
子句限定了我们只关心那些视频ID分别为"1001"和"1002"的记录,并要求"1001"的观看时长大于"1002"的。DISTINCT
关键字确保每个符合条件的用户ID只被列出一次,避免重复
SELECT distinct vv1.user_id
FROM video_records vv1
JOIN video_records vv2 ON vv1.user_id = vv2.user_id WHERE vv1.video_id = "1001" AND vv2.video_id = "1002"and vv1.play_duration > vv2.play_durationvideo_records
执行结果:
感谢各位的观看,创作不易,能不能给哥们来一个点赞呢!!!
好了,今天的分享就这么多了,有什么不清楚或者我写错的地方,请多多指教!
私信,评论我呗!!!!!!
关注我下一篇不迷路哦!