mysql / php: mantener un registro adicional durante la paginación
Pregunta
Tengo una lista de registros por los que quiero pasar páginas usando LIMIT, sin embargo, el primer registro que se devuelve sin LIMIT también es el identificador raíz para el resto de los registros y necesito mantenerlo para cada página. es posible? (Prefiero no ejecutar una instrucción SQL adicional)
id | index | title
1 | 0 | index of titles
2 | 1 | title1
3 | 1 | title2
4 | 1 | title3
5 | 1 | title4
LÍMITE 3, 2 debería volver ...
id | index | title
1 | 0 | index of titles
4 | 1 | title3
5 | 1 | title4
Solución
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
Si tiene una clave compuesta en (index, id)
(en MyISAM
) o simplemente un índice en index
(en InnoDB
), la primera consulta no costará casi nada.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow