2017-05-09 94 views
-1

我的下面的查詢給了我過去2小時播放的頂級視頻的結果,但是我的要求是也獲得過去4小時的頂級視頻到過去2小時,例如如果通過這個查詢,我從01:00 PM到03:00 PM獲取數據,我還希望從09:00 AM到01:00 PM的數據。我可以在一個查詢中以高效的方式做到這一點。Mysql - 在同一個查詢中獲取不同時間間隔的數據

查詢:

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; 
+0

此查詢將使我的原始查詢時間加倍。 – Vaibhav

+0

對不起,沒有得到你。你在談論執行時間嗎? –

+0

是,執行時間。 – Vaibhav

相關問題