I have the following situation:
In a table I have 4 columns:
CommentsTBL:
ID int
Data datetime
Hour Varchar
Comment Varchar
The Hour column is of varchar type, don't ask me why....
Given a specific date and hour from the table, I need to find the previous and the next record. If I will find one of them (previous or next) it will be simple to get the other one using the same logic.
As an example:
ID Data Hour Comment
1. 2011-01-12 17:00 SomeComments1
2. 2011-01-14 10:00 SomeComments3
3. 2011-01-14 11:00 SomeComments4
4. 2011-01-13 14:00 SomeComments2
The previous date for ID 4 would be ID 1 and the next one will be ID 2.
I came up with a solution for this, but I want to see if any of you have something better, maybe using just one SELECT. This is for the previous one:
SELECT
Data,
MAX(Hour) Hour
FROM
CommentsTBL
WHERE
Data in (SELECT
MAX(Data)
FROM
CommentsTBL
开发者_运维技巧WHERE
Data < MyDate or (Data = MyDate and Hour < MyHour)
)
GROUP BY
Data
Thanks.
Why not:
select *
from ( SELECT data, hour from commentsTbl
where data < mydate
or ( data = mydate and hour < myhour )
order by data desc, hour desc
limit 1
)
union all
select *
from ( SELECT data, hour from commentsTbl
where data > mydate
or ( data = mydate and hour > myhour )
order by data asc, hour asc
limit 1
)
精彩评论