我的下面的查询给出了过去2小时内播放的热门视频的结果,但我的要求是获得过去4小时到过去2小时的热门视频,例如,如果通过此查询我从01获取数据:下午00点到下午03点,我也想要从上午9点到下午01点的数据。我可以在一个查询中以有效的方式执行此操作。
查询:
select SQL_CACHE channel,SUBSTRING_INDEX(GROUP_CONCAT(video_id ORDER BY plays DESC),',', 40) AS video_ids,now() as datetime from
(SELECT channel,video_id,count(video_id) as plays FROM `tbl`
WHERE `datetime_col` > DATE_SUB( now(), INTERVAL 2 HOUR )
and channel != 0
and cat_id != 8
group by channel,video_id
order by channel,plays DESC)x
group by channel;
提前致谢。
答案 0 :(得分:0)
您可以对UNION
使用相同的查询对结果进行分组。此外,您可以使用BETWEEN
来定义间隔,例如
select SQL_CACHE channel,SUBSTRING_INDEX(GROUP_CONCAT(video_id ORDER BY plays DESC),',', 40) AS video_ids,now() as datetime from
(SELECT channel,video_id,count(video_id) as plays FROM `tbl`
WHERE `datetime_col` BETWEEN DATE_SUB( now(), INTERVAL 2 HOUR ) AND NOW()
and channel != 0
and cat_id != 8
group by channel,video_id
order by channel,plays DESC)x
group by channel
UNION
select SQL_CACHE channel,SUBSTRING_INDEX(GROUP_CONCAT(video_id ORDER BY plays DESC),',', 40) AS video_ids,DATE_SUB( now(), INTERVAL 2 HOUR ) as datetime from
(SELECT channel,video_id,count(video_id) as plays FROM `tbl`
WHERE `datetime_col` BETWEEN DATE_SUB( now(), INTERVAL 4 HOUR ) AND DATE_SUB( now(), INTERVAL 2 HOUR )
and channel != 0
and cat_id != 8
group by channel,video_id
order by channel,plays DESC)x
group by channel;