从MySQL获得更新和更旧的帖子,但至少有一定数量

时间:2013-06-05 09:44:41

标签: mysql

我有一个这样的数据库:

+------------+-------------+
| listed     | data        |
+------------+-------------+
| 2013-01-01 | random text |
| 2013-01-02 | random text |
| 2013-01-03 | random text |
| 2013-01-05 | random text |
| 2013-01-06 | random text |
| 2013-01-07 | random text |
+------------+-------------+

在这种情况下,“数据”是一个笑话的标题。我想列出当前玩笑旁边的旧笑话和新笑话。不是每天都开个玩笑。如果没有新的,我想要更老的和反对的......

这样:

   for 2013-01-02 I want 2013-01-01 and 2013-01-03
   for 2013-01-03 I want 2013-01-02 and 2013-01-05
   for 2013-01-07 I want 2013-01-05 and 2013-01-06
   for 2013-01-01 I want 2013-01-02 and 2013-01-03

我可以在两个查询中执行此操作,在其他查询未返回任何内容时至少获取2个笑话:

SELECT * FROM jokes WHERE listed>'$date' ORDER BY listed ASC limit 2
SELECT * FROM jokes WHERE listed<'$date' ORDER BY listed DESC limit 2

然后对数组的长度进行数学计算,但我想知道是否有一种正确的方法可以在单个查询中执行此操作?

1 个答案:

答案 0 :(得分:1)

在这里查看SQL Fiddle。我发布了一个非常大的查询解决方案。但我认为有人可以减小它的大小。

SELECT * FROM (SELECT 
   listed,DATA,@r2 := @r2 + 1 AS num
FROM 
  jokes,
  (SELECT @r2:=0) AS e) t WHERE FIND_IN_SET(num,(SELECT FOUND FROM (SELECT 
    listed,`data`,@rn := @rn + 1 AS number,
    IF(listed = '2013-01-07',#pass your date here
        IF(@rn = 1,CONCAT(2,',',3),
            IF(@rn = (SELECT COUNT(*) FROM jokes),CONCAT(@rn-1,',',@rn-2),CONCAT(@rn-1,',',@rn+1)))    ,-1) 
        AS `found`
FROM jokes,(SELECT @rn := 0 ) r

ORDER BY listed ) AS k  WHERE `found` != -1))>0