I have a table containing calendar items; in my web application, I have two views:
- View 1: primary view that shows the next 10 items, starting from now
- View 2: view that shows the previous/next 10 items based on the timestamp of the first/last item in view 1. This is the troublemaker.
On the bottom of the page, previous/next links are shown that lead to view 2.
The problem:
How do I retrieve the previous set of 10 items without knowing what date they are?
At first, this seemed quite simple to me, but apparently, it is not.
Database table:
+-------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+----------------+
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | MUL | NULL | |
| start_time | datetime | YES | | NULL | |
| end_time | datetime | YES | | NULL | |
| created | datetime | NO | | NULL | |
| updated | datetime | YES | | NULL | |
| deleted | tinyint(1) | NO | | 0 | |
+-------------+------------------+------+-----+---------+----------------+
SQL query for showing next 10 items starting from now (no problems here):
SELECT ci.*
FROM `calendar_item` AS `ci`
WHERE ci.end_time >= NOW()
GROUP BY `ci`.`id`
ORDER BY `ci`.`end_time` ASC
LIMIT 10
SQL query for showing previous 10 items, based on timestamp of the 1st item in the primary view:
SELECT ci.*
FROM `calendar_item` AS `ci`
WHERE (ci.id IN (
SELECT id FROM calendar_item
WHERE (end_time < FROM_UNIXTIME(1334667600))
ORDER BY end_time DESC
))
GROUP BY `ci`.`id`
ORDER BY `ci`.`end_time` ASC
LIMIT 10
The timestamp is passed via the URL; in view 1 the subquery is not shown at all. The problem lies in the fact that items should be sorted ascending; this would result in the earliest items in the database being returned, instead of the nearest to timestamp. To counter this problem, I created a subquery that sorts descendingly. This subquery works fine when I run it as a normal query, but when contained by the above query, it simply displays the same results as would the following:
SELECT ci.*
FROM `calendar_item` AS `ci`
WHERE ci.end_time <= 1334667600
GROUP BY `ci`.`id`
ORDER BY `ci`.`end_time` ASC
LIMIT 10
I am most likely overlooking something, so I could use your help. Thanks in advance.
This is a simple one, LIMIT the subquery
Without the limit in the subquery you are selecting ALL rows with a timestamp < FROM_UNIXTIMESTAMP. You are then reordering ASC and selecting the first 10, i.e. the earliest 10.
If you limit the subquery you get the 10 highest which satisfy your FROM_UNIXTIME, and the outer can then select them.
An alternative (and my preferred) would be the following, where the subquery gets the data, and the outer query simply reorders it before spitting it back out.