2012-01-21 56 views
0

*修訂,但仍然沒有解決... *MySQL的 - JOIN或UNION - 不知道這,也許兩者(第二部分)

我想將數據從兩個文件合併,但我無法表達這種排序。我想對來自第一個文件的CREATED日期和來自第二個文件的SHARED_DATE進行排序,如果它存在並且它更大。

file 1 : NODE 
fields: CREATED, CHANGED 

file 2 : SHARE_CONTENT 
fields: SHARED_DATE , NODE (foreign key) 

...

SELECT n.created, s.shared_date, 

(CASE WHEN s.shared_date <> NULL 
    then s.shared_date 
    else n.created 
END) 
as lastshare 

FROM node as n LEFT JOIN share_content as s on (s.nid=n.nid) 

ORDER BY lastshare DESC 

另一種可能性..

SELECT n.created, s.shared_date, 
FROM node as n LEFT JOIN share_content as s on (s.nid=n.nid) 
ORDER BY MAX(n.created, s.shared_date) DESC 

除了MySQL的似乎並不像Max(A,B)

+0

'MAX(..)'只能用'集團by' – rauschen

回答

0
SELECT n.created, s.shared_date, 
(CASE WHEN (s.shared_date IS NOT NULL) And (s.Shared_Date > n.Created) 
    then s.shared_date 
    else n.created 
END) 
as lastshare 
FROM node as n LEFT JOIN share_content as s on (s.nid=n.nid) 
ORDER BY lastshare DESC 

特別注意的不是<>。 NULL在SQL中非常非常特殊。

+0

工作,我會說出我的第一個孩子STU !!!!! –

+0

只有當它是一個男孩,請。如果我在幾年內遇到一個名叫Stu的小女孩,我會非常非常興奮! – Stu

+0

我們會打電話給她Sue! (這是一個便宜的約翰尼現金笑話http://www.youtube.com/watch?v=-1BJfDvSITY) –

0
SELECT n.created, s.shared_date, 

(CASE WHEN s.shared_date IS NOT NULL 
    THEN 
     (CASE WHEN s.shared_date > n.created 
     THEN s.shared_date ELSE n.created END) 
    ELSE n.created 
END) 
as lastshare 

FROM node as n LEFT JOIN share_content as s on (s.nid=n.nid) 

ORDER BY lastshare DESC 

現在它應該像你想;)