1

我有一个要使用 LIMIT 分页的记录列表,但是没有 LIMIT 返回的第一条记录也是其余记录的根标识符,我需要为每一页保留它。这可能吗?(我只是不想运行额外的 sql 语句)

id  |  index  |  title
1   |  0      |  index of titles
2   |  1      |  title1
3   |  1      |  title2
4   |  1      |  title3
5   |  1      |  title4

LIMIT 3, 2 应该返回...

id  |  index  |  title
1   |  0      |  index of titles
4   |  1      |  title3
5   |  1      |  title4
4

1 回答 1

3
SELECT  *
FROM    (
        SELECT  *
        FROM    mytable
        WHERE   index = 0
        ORDER BY
                index, id
        LIMIT 1
        ) q
UNION ALL
        (
        SELECT  *
        FROM    mytable
        WHERE   index = 1
        ORDER BY
                index, id
        LIMIT 3, 2
        ) q2

如果您在 (in ) 上有一个复合键或在( (index, id)in MyISAM) 上有一个索引,那么第一个查询几乎不会花费任何成本。indexInnoDB

于 2009-08-04T10:07:46.910 回答