0

我熟悉分页,因为我可以根据页码选择一组用户,如下所示:

// setup pagination
$page = 1;
$display = 5;
$start = $display * $page - $display;

$sql = "SELECT * FROM users WHERE valid = 'Y' ORDER BY :username ASC LIMIT :start, :display";
$sth = $this->db->prepare($sql);
$sth->bindValue(':username', $username, PDO::PARAM_STR);
$sth->bindValue(':start', $start, PDO::PARAM_INT);
$sth->bindValue(':display', $display, PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);

我想弄清楚的是如何做类似的事情,而不是我有一个用户 ID 的页码。例如,给定用户 ID“3”和“3”的显示限制,我想选择该用户以及紧接在字母前后的用户(总共三个用户)。我希望这是有道理的..

关于如何解决这个问题的任何建议?

4

2 回答 2

3

这是一种结合使用三个子查询的方法union all

(select *
 from users
 where valid = 'Y' and username < :username
 order by username desc
 limit 1
)
union all
(select *
 from users
 where valid = 'Y' and username = :username
 order by username desc
 limit 1
)
union all
(select *
 from users
 where valid = 'Y' and username > :username
 order by username
 limit 1
)
于 2013-05-15T23:15:28.737 回答
2

这是一个想法...

SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+

(SELECT * FROM ints WHERE i >= 3 ORDER BY i LIMIT 2) 
UNION 
(SELECT * FROM ints WHERE i < 3 ORDER BY i DESC LIMIT 1) 
ORDER BY i;
+---+
| i |
+---+
| 2 |
| 3 |
| 4 |
+---+
于 2013-05-15T23:15:50.410 回答