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

MySQL SELECT id della riga in cui GREATEST of MAX voci di diverse colonne

un modo per farlo sarebbe memorizzare la data in una variabile definita dall'utente. quindi puoi usarlo per estrarre l'ID per la data più grande

SET @A := (SELECT GREATEST(
                     IFNULL(max(date1), 0),
                     IFNULL(max(date2), 0),
                     IFNULL(max(date3), 0)
                  ) FROM table1
           );
-- here i JOIN a select that pulls out the correct id
SELECT t.joinid, max(`date1`), max(`date2`), max(`date3`)
FROM table1
JOIN 
(   SELECT id as joinid 
    FROM table1
    WHERE @A IN -- WHERE my MAX date is in
    (
        SELECT date1 -- here the UNION is just putting all of the dates into one column to compare one date with
        UNION ALL SELECT date2
        UNION ALL SELECT date3
    )
) t -- every table must have an alias

DEMO FIDDLE