1

我有一个这样的数据库:

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

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

4

1 回答 1

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
于 2013-06-05T11:27:39.437 回答