views:

160

answers:

1

I need a single query that is similar to

SELECT datetime FROM blog WHERE UNIX_TIMESTAMP(datetime) < '".($date_string_in_seconds +1000)."' ORDER BY datetime DESC

but instead of returning the latest date that is smaller than the one given in parameter, it has to return:
-the record with the exact date that is given in the parameter
-if exists, one with the earliest timestamp that is higher than the parameter
-if exists, one with the latest timestamp that smaller than the parameter (what the query above returns)
In other words, it should return the given date and the ones right after and before that. The query should return at most three and at least one record with a valid date.

I need this information as a basis for enabling/disabling prev and next entry buttons on a blog page and currently get the information with two separate queries.
I suspect there is a better way. Is this possible with a single query?

+1  A: 
SELECT  datetime
FROM    (
        SELECT  datetime
        FROM    blog
        WHERE   datetime < FROM_UNIXTIME($date)
        ORDER BY
                datetime DESC
        LIMIT 1
        ) p
UNION ALL
SELECT  datetime
FROM    blog
WHERE   datetime = FROM_UNIXTIME($date)
UNION ALL
SELECT  datetime
FROM    (
        SELECT  datetime
        FROM    blog
        WHERE   datetime > FROM_UNIXTIME($date)
        ORDER BY
                datetime
        LIMIT 1
        ) n
Quassnoi
exactly. thanks a bunch!
Şafak Gezer