What about this ?
SELECT T1.f1 as "date 1", T2.f1 as "date 2", T3.f1 as "date 3"
FROM (SELECT *
FROM `date_test`
ORDER BY `f1` DESC
LIMIT 1) AS T1,
(SELECT *
FROM `date_test`
ORDER BY `f1` DESC
LIMIT 1, 1) AS T2,
(SELECT *
FROM `date_test`
ORDER BY `f1` DESC
LIMIT 2, 1) AS T3
;
Which outputs :
+------------+------------+------------+
| date 1 | date 2 | date 3 |
+------------+------------+------------+
| 2003-01-01 | 2002-01-01 | 2001-01-01 |
+------------+------------+------------+
The only downside is that you need at least three rows, otherwise it won't return anything...
Using JOIN
, you can do this :
SELECT T1.id,
T1.f1 as "date 1",
T2.f1 as "date 2",
T3.f1 as "date 3"
FROM `date_test` as T1
LEFT JOIN (SELECT * FROM `date_test` ORDER BY `f1` DESC) as T2 ON (T1.id=T2.id AND T1.f1 != T2.f1)
LEFT JOIN (SELECT * FROM `date_test` ORDER BY `f1` DESC) as T3 ON (T1.id=T3.id AND T2.f1 != T3.f1 AND T1.f1 != T3.f1)
GROUP BY T1.id
ORDER BY T1.id ASC, T1.f1 DESC
Which will return something like :
+----+------------+------------+------------+
| id | date 1 | date 2 | date 3 |
+----+------------+------------+------------+
| 1 | 2001-01-01 | 2003-01-01 | 2002-01-01 |
+----+------------+------------+------------+
The downside is that date1
, date 2
and date 3
will not necessarily be in a specific order (as per the above sample output). But this can be achieved programatically. The plus side is that you can insert a WHERE
clause before the GROUP BY
and you can search by T1.id
, for example.