根据两个文本列排序的SQL获取下一行和上一行

时间:2015-02-02 19:17:41

标签: mysql sql

我有这个sql语句:

SELECT * FROM members ORDER BY last_name ASC, first_name ASC LIMIT 0, 10

以上用于索引页面。

在详细信息页面上,我使用

SELECT * FROM members WHERE id = :id

如何根据当前行ID获取上一行和下一行? (由last_name ASC,first_name ASC排序的上一个和下一个)

我认为它会是这样的:

SELECT id FROM members WHERE last_name >= : last_name AND id != :id ORDER BY last_name ASC, first_name ASC

但那不对。我还需要以某种方式将first_name添加到语句中,并且只是执行first_name> =:first_name不正确。

1 个答案:

答案 0 :(得分:1)

您可以将union allorder bylimit一起使用。以下内容在第一个子查询中获取先前的名称,在第二个子查询中获取下一个名称:

(select m.*
 from members m
 where last_name < (select last_name from members where id = :id)
 order by last_name desc
 limit 1
) union all
(select m.*
 from members m
 where last_name > (select last_name from members where id = :id)
 order by last_name asc
 limit 1
);

处理名字和姓氏的最简单方法可能是将它们连接在一起:

(select m.*
 from members m
 where concat_ws(' ', last_name, first_name) < (select concat_ws(' ', last_name, first_name) from members where id = :id)
 order by last_name asc, first_name desc
 limit 1
) union all
(select m.*
 from members m
 where concat_ws(' ', last_name, first_name) > (select concat_ws(' ', last_name, first_name) from members where id = :id)
 order by last_name asc, first_name
 limit 1
)

如果第一个和/或最后一个名称中包含空格,则可能会出现意外结果。我猜测数据中没有发生这种情况,但在这种情况下可以使用其他分隔符。