我需要进行一个查询,根据最后和最后一个搜索时间输出数据。让我解释一下表格:
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的最后搜索到的和最后搜索到的第二个comp名称...我真的很无奈在这种情况下如何继续....任何人都可以指导我这个......
答案 0 :(得分: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