I got
TableA
| id | san | status | created |
-------------------------------------------
| 1 | 100 | 3 | 2013-11-01 19:26:20 |
| 2 | 200 | 8 | 2013-11-02 03:19:35 |
| 3 | 300 | 1 | 2013-11-03 06:13:38 |
| 4 | 100 | 2 | 2013-11-06 08:28:37 |
| 5 | 100 | 4 | 2013-11-27 19:00:00 |
| 6 | 200 | 1 | 2013-11-27 19:16:22 |
| 7 | 200 | 3 | 2013-11-27 19:33:33 |
| 8 | 300 | 5 | 2013-11-27 19:50:29 |
TableB
| san | san-name |
------------------
| 100 | xxx1 |
| 200 | xxx2 |
| 300 | xxx3 |
with this query (using union all because i have tons of rows)
SELECT id, max(lastdate) AS lastdate, max(san) AS san
FROM
(SELECT `san` AS id,
`created` AS lastdate,
'' AS san
FROM `TableA` a
UNION ALL
SELECT `san` AS id,
cast(null as datetime) AS lastdate,
`san-name` AS san
FROM `TableB` b
) sq
GROUP BY id
ORDER BY san ASC
i get this result (everything works perfect)
| id | lastdate | san |
--------------------------------------
| 100 | 2013-11-27 19:00:00 | xxx1 |
| 200 | 2013-11-27 19:33:33 | xxx2 |
| 300 | 2013-11-27 19:50:29 | xxx3 |
but now i want to add also the "status" of the latest "created" "id" into my result.
from TableA i want the rows ( see <- LATEST SAN ..... )
| id | san | status | created |
-------------------------------------------
| 1 | 100 | 3 | 2013-11-01 19:26:20 |
| 2 | 200 | 8 | 2013-11-02 03:19:35 |
| 3 | 300 | 1 | 2013-11-03 06:13:38 |
| 4 | 100 | 2 | 2013-11-06 08:28:37 |
| 5 | 100 | 4 | 2013-11-27 19:00:00 | <- LATEST SAN 100
| 6 | 200 | 1 | 2013-11-27 19:16:22 |
| 7 | 200 | 3 | 2013-11-27 19:33:33 | <- LATEST SAN 200
| 8 | 300 | 5 | 2013-11-27 19:50:29 | <- LATEST SAN 300
and it should look like this:
| id | status | lastdate | san |
------------------------------------------------
| 100 | 4 | 2013-11-27 19:00:00 | xxx1 |
| 200 | 3 | 2013-11-27 19:33:33 | xxx2 |
| 300 | 5 | 2013-11-27 19:50:29 | xxx3 |
i tried it with this code
SELECT id, status, max(lastdate) AS lastdate, max(san) AS san
FROM
(SELECT `san` AS id,
`created` AS lastdate,
'' AS san,
status AS status
FROM `TableA` a
UNION ALL
SELECT `san` AS id,
cast(null as datetime) AS lastdate,
`san-name` AS san,
'' AS status
FROM `TableB` b
) sq
GROUP BY id
ORDER BY san ASC
but it gives me this (WRONG RESULT)
| id | status | lastdate | san |
------------------------------------------------
| 100 | 3 | 2013-11-27 19:00:00 | xxx1 |
| 200 | 8 | 2013-11-27 19:33:33 | xxx2 |
| 300 | 1 | 2013-11-27 19:50:29 | xxx3 |
and not the right one like this
| id | status | lastdate | san |
------------------------------------------------
| 100 | 4 | 2013-11-27 19:00:00 | xxx1 |
| 200 | 3 | 2013-11-27 19:33:33 | xxx2 |
| 300 | 5 | 2013-11-27 19:50:29 | xxx3 |
could somebody help me? :o)
i created a sqlfiddle
best regards
bernte