在无序行集上选择Next或上一行

时间:2013-07-20 10:03:11

标签: mysql

我有一个UNION SQL查询,可以生成无序的行集。结果与之相同

+----+----------------------+-------+
| id | name                 | value |
+----+----------------------+-------+
| 3  | John                 | 21    |
+----+----------------------+-------+
| 2  | Jim                  | 5     |
+----+----------------------+-------+
| 4  | Adrian               | 25    |
+----+----------------------+-------+
| 1  | Sam                  | 22    |
+----+----------------------+-------+

如果选择了第二行,我如何选择下一行或上一行?

1 个答案:

答案 0 :(得分:1)

MySql中缺少rownum函数的常用技巧:

SELECT
    @rownum:=@rownum+1 AS rownum, 
    id, name, value
FROM
    (
        (SELECT id, name, value FROM buyers ORDER BY id) 
        UNION
        (SELECT id, name, value FROM seller ORDER BY id) 
    ) subq,
    (SELECT @rownum:=0) r;

然后使用rownum字段在行之间导航。