mysql选择n行之前和n行之后

时间:2013-12-07 15:37:18

标签: php mysql union

我正在尝试创建一个mysql查询来选择让我们说前5行和5行,具体取决于当前ID。这是我想要使用的查询:

SELECT * FROM posts WHERE PID<='10' ORDER BY PID DESC LIMIT 7
UNION ALL
SELECT * FROM posts WHERE PID>'10' ORDER BY PID ASC LIMIT 6

但出于某种原因,查询无效。我错过了什么吗?我在论坛帖子中找到了这个解决方案。

3 个答案:

答案 0 :(得分:1)

PID可能是 int 类型。所以你应该使用以下( SQL Fiddle ):

(SELECT * FROM posts WHERE PID <= 10 ORDER BY PID DESC LIMIT 7)
UNION ALL
(SELECT * FROM posts WHERE PID > 10 ORDER BY PID ASC LIMIT 6)

正如您所看到的,两个查询的顺序也是单独维护的。

答案 1 :(得分:1)

试试这个:

(SELECT *
 FROM posts
 WHERE PID <= '10'
 ORDER BY PID DESC LIMIT 7
 )
UNION ALL
(SELECT *
 FROM posts
 WHERE PID > '10'
 ORDER BY PID ASC LIMIT 6
 )
ORDER BY PID ASC;

sqlfiddle demo

答案 2 :(得分:0)

DOCS

  

要将ORDER BY或LIMIT应用于单个SELECT,请将该子句放在括起SELECT的括号内: