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

MySQL:seleziona riga per ID con la riga precedente e successiva per data

Primo approccio. Questa selezione restituisce 3 righe. La riga selezionata e una riga per una data precedente e una riga anoder per la data successiva:

SELECT * FROM ( 
 SELECT 
   'THIS' as update_time,
   update_id, 
   project_id, 
   content, 
   date
 FROM 
   `update`
 WHERE 
   update_id = 2 AND project_id = 2
 ORDER 
   BY date DESC
 LIMIT 1
) TT
UNION
SELECT * FROM ( 
 SELECT 
   'PREVIOUS'  as update_time,
   update_id, 
   project_id, 
   content, 
   date
 FROM 
   `update`
 WHERE 
   update_id <> 2 AND project_id = 2 and
   date <= (select date from `update` where update_id = 2)
 ORDER 
   BY date DESC
 LIMIT 1
) TP
UNION
SELECT * FROM ( 
 SELECT 
   'NEXT'  as update_time,
   update_id, 
   project_id, 
   content, 
   date
 FROM 
   `update`
 WHERE 
   update_id <> 2 AND project_id = 2 and
   date >= (select date from `update` where update_id = 2)
 ORDER 
   BY date ASC
 LIMIT 1
) TN