我熟悉分页,因为我可以根据页码选择一组用户:
// 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”,我想在字母顺序之前和之后立即选择该用户以及用户(总共三个用户)。我希望这是有道理的。
有关如何处理此事的任何建议吗?
答案 0 :(得分: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
)
答案 1 :(得分: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 |
+---+