我有一个这样的数据库:

+------------+-------------+
| 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

我可以在两个查询中完成此操作,如果另一个查询不返回任何内容,则至少获得两个笑话:
SELECT * FROM jokes WHERE listed>'$date' ORDER BY listed ASC limit 2
SELECT * FROM jokes WHERE listed<'$date' ORDER BY listed DESC limit 2

然后计算数组的长度,但我想知道在一个查询中是否有合适的方法来完成这个任务?

最佳答案

检查这里。我已经发布了一个非常大的查询的解决方案。但是我认为有人可以减小它的大小。

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

关于mysql - 从MySQL获得更新和较旧的帖子,但至少有一定数量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16936611/

10-12 17:32