Long story short, I'm trying to get the time my site was last updated. The main content of my site is stored in four tables. Each of 开发者_如何学运维these tables has an updated_at field.
I'm able to combine them in a nested query:
SELECT (
SELECT updated_at FROM proposition ORDER BY updated_at DESC LIMIT 1
) as latest_proposition,
(
SELECT updated_at FROM product ORDER BY updated_at DESC LIMIT 1
) as latest_product,
(
SELECT updated_at FROM review ORDER BY updated_at DESC LIMIT 1
) as latest_review,
(
SELECT updated_at FROM segment ORDER BY updated_at DESC LIMIT 1
) as latest_segment
..which gives me something like..
-------------------+-------------------+-------------------+-------------------
latest_proposition |latest_product |latest_review |latest_segment
-------------------+-------------------+-------------------+-------------------
2011-05-25 14:45:30|2011-05-25 14:37:28|2011-05-12 09:20:19|2011-05-12 09:20:19
-------------------+-------------------+-------------------+-------------------
1 row in set (0.00 sec)
My question is - How do I now get the latest of these fields? To get the overall "site last updated" time.
Thanks in advance!
select
max(updated_at) as updated_at
from
(
SELECT max(updated_at) as updated_at FROM proposition
UNION
SELECT max(updated_at) FROM product
UNION
SELECT max(updated_at) FROM review
UNION
SELECT max(updated_at) FROM segment
) x
Use GREATEST() on the returned fields (after passing them through COALESCE(), if you expect NULL
values).
SELECT updated_at
from
(
SELECT updated_at FROM proposition ORDER BY updated_at DESC LIMIT 1
union all
SELECT updated_at FROM product ORDER BY updated_at DESC LIMIT 1
union all
SELECT updated_at FROM review ORDER BY updated_at DESC LIMIT 1
union all
SELECT updated_at FROM segment ORDER BY updated_at DESC LIMIT 1
) x
order by updated_at limit 1
SELECT MAX(updated_at)
FROM (SELECT MAX(updated_at) FROM proposition UNION ALL
SELECT MAX(updated_at) FROM product UNION ALL
SELECT MAX(updated_at) FROM review UNION ALL
SELECT MAX(updated_at) FROM segment) x
精彩评论