2011-05-26 189 views
0

長話短說,我試圖讓我的網站上次更新的時間。 我的網站的主要內容存儲在四個表格中。 每個表都有一個updated_at字段。嵌套嵌套? MySQL查詢幫助

我能夠向他們嵌套查詢相結合:

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 

..這讓我有點像..


-------------------+-------------------+-------------------+------------------- 
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) 

我的問題是 - 如何我現在得到的最新這些領域的?獲取整個「網站上次更新」時間。

在此先感謝!

+1

我覺得你是一個工會之後。 – Andrew 2011-05-26 10:43:40

回答

4
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 
+0

@GolexTrol,使用'UNION ALL',否則MySQL將(嘗試)消除重複行,這將減慢查詢速度。 – Johan 2011-05-26 11:24:40

+0

是的,那是真的。通過這種方式,試圖從總共4箇中消除重複的內容並不會那麼大。此外,更少的行將加快檢索主查詢中的最大值。 (理論上只處理4行)。但確實很好。 UNION ALL通常比UNION更好,幾乎沒有更糟。 – GolezTrol 2011-05-27 05:06:26

0
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 
0
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 
+0

你需要在子選擇中將字段別名。正如我所做的那樣; *) – GolezTrol 2011-05-26 10:49:36