sql >> Database teknologi >  >> RDS >> Mysql

Hvordan finder man tidligere post [n-per-group max(timestamp)

Den sidste tilgang med variabler er rimelig. Du kan også prøve:

SELECT collect.*,
       (select max(timestamp)
        from data
        where data.channel_id = collect.channel_id AND data.timestamp < collect.timestamp
       ) AS prev_timestamp
FROM data AS collect 
WHERE collect.channel_id = 14 AND collect.timestamp >= 0 
ORDER BY collect.timestamp;

Derudover skal du oprette indekser på:collect(channel_id, timestamp).

EDIT:

Følgende kan være den hurtigste:

  select d.*,
         if(@channel_id = channel_id, @prev_timestamp, NULL) as prev_timestamp,
         @channel_id := channel_id, @prev_timestamp = timestamp
  from data d cross join
       (select @channel_id := 0, @prev_timestamp := 0) vars
  where collect.channel_id = 14 AND collect.timestamp >= 0 
  order by channel_id, timestamp;



  1. Låsning af et bord med dvale

  2. Sådan indsætter du JSON i en tabel i SQL Server

  3. Hvordan konverteres tal til streng i Oracle?

  4. At gemme billedfiler i Mongo-databasen, er det en god idé?