MySQL:按ID排序,按日期排序前一行和下一行

时间:2011-12-29 21:17:48

标签: mysql

我有这张桌子:

update_id | project_id | content | date
------------------------------------------------------
1         | 1          | text... | 2011-12-20 22:10:30 
2         | 2          | text... | 2011-12-20 22:10:30 
3         | 2          | text... | 2011-12-21 22:10:30 
4         | 2          | text... | 2011-12-22 22:10:30 
5         | 2          | text... | 2011-12-23 22:10:30 

我目前的查询是:

SELECT update_id, project_id, content, date
FROM update
WHERE update_id = 2
AND project_id = 2
ORDER BY date DESC
LIMIT 1

但是除了选定的行之外,我还想根据日期列(针对特定的project_id)获取上一行和下一行,因此我可以显示“上次更新”和“下次更新”链接(如果可用)。

2 个答案:

答案 0 :(得分:1)

第一种方法。这个选择返回3行。您选择的行和上一个日期的行和下一个日期的anoder行:

SELECT * FROM ( 
 SELECT 
   'THIS' as update_time,
   update_id, 
   project_id, 
   content, 
   date
 FROM 
   `update`
 WHERE 
   update_id = 2 AND project_id = 2
 ORDER 
   BY date DESC
 LIMIT 1
) TT
UNION
SELECT * FROM ( 
 SELECT 
   'PREVIOUS'  as update_time,
   update_id, 
   project_id, 
   content, 
   date
 FROM 
   `update`
 WHERE 
   update_id <> 2 AND project_id = 2 and
   date <= (select date from `update` where update_id = 2)
 ORDER 
   BY date DESC
 LIMIT 1
) TP
UNION
SELECT * FROM ( 
 SELECT 
   'NEXT'  as update_time,
   update_id, 
   project_id, 
   content, 
   date
 FROM 
   `update`
 WHERE 
   update_id <> 2 AND project_id = 2 and
   date >= (select date from `update` where update_id = 2)
 ORDER 
   BY date ASC
 LIMIT 1
) TN

答案 1 :(得分:0)

您需要2个子选择..但现在要链接它们。

SELECT @rownum:=@rownum+1 as place, update_id, project_id, content, date, () as previous, () as next, (SELECT @rownum:=0)

其中blank()由相同形式的子查询替换。