2015-04-12 52 views
1

我需要做一個查詢,它將根據上一次和第二次搜索時間輸出數據。讓我解釋一下表:帶有時間戳的分組mysql查詢

id key   comp timestamp 
1 keyword1 comp1 11-04-2015 23:56 
2 keyword2 comp3 12-04-2015 23:56 
3 keyword1 comp2 12-04-2015 00:56 
4 keyword3 comp4 11-04-2015 23:56 
5 keyword3 comp6 11-04-2015 23:56 

現在,輸出應爲:

keyword1 comp1 11-04-2015 23:56 comp2 12-04-2015 00:56 

意味着我需要顯示的最後搜查,倒數第二個搜索的關鍵字1的補償名字......我就真的很無奈這種情況下,如何進行....任何一個可以請指導我這個...

回答

2
select r1.key 
,  r1.comp 
,  r1.timestamp 
,  r2.key 
,  r2.comp 
,  r2.timestamp 
from (
     select * 
     from YourTable 
     where `key` = 'keyword1' 
     order by 
       timestamp desc 
     limit 1 -- First row 
     ) r1 
left join 
     (
     select * 
     from YourTable 
     where `key` = 'keyword1' 
     order by 
       timestamp desc 
     limit 1, 1 -- Skip 1, take 1 --> second row 
     ) r2 
on  1=1 

See it working at SQL Fiddle.