sql >> Base de Datos >  >> RDS >> Mysql

MYSQL Seleccione 5 registros para los últimos 5 registros distintos

En muchos otros DBMS (Oracle, SQL-Server, Postgres) podría usar funciones de ventana:

SELECT id, file, folder, added
FROM
  ( SELECT id, file, folder, added,
           DENSE_RANK() OVER (ORDER BY added DESC) AS d_rank,
           ROW_NUMBER() OVER (PARTITION BY added ORDER BY id DESC) AS row_no
    FROM AviationImages
  ) d
WHERE d_rank <= 5          -- limit number of dates
  AND row_no <= 5 ;        -- limit number of images per date

En MySQL no tienes el lujo de la función de ventana y OVER cláusula:

SELECT i.id, i.file, i.folder, i.added
FROM
    ( SELECT DISTINCT added
      FROM AviationImages
      ORDER BY added DESC
      LIMIT 5
    ) AS da
  JOIN
    AviationImages AS i
      ON  i.added = da.added
      AND i.id >= COALESCE(
          ( SELECT ti.id
            FROM AviationImages AS ti
            WHERE ti.added = da.added
            ORDER BY ti.id DESC
            LIMIT 1 OFFSET 4
          ), -2147483647) ;             -- use 0 if the `id` is unsigned int

Un índice en (added, id) ayudará a la eficiencia, y si la tabla usa InnoDB y el id es la clave principal, luego solo un índice en (added) será suficiente.