2012-08-27 52 views
1

我想選擇使用工會從不同的表中的項目,通過他們的日期(最新的在前)工會選擇和ORDER BY與MySQL

說我有以下各表

events 
eventsID | eventsTitle  | eventsTimestamp | eventsLocation 
1   event title   2012/08/23   1 
2   event title 2  2012/08/15   1 


posts 
postsID | postsSubject | postsTimestamp | postsCategory 
1   post title  2012/08/20   1 

於是下令輸出應該是

title   timestamp 
event Title  2012/08/23 
post title  2012/08/20 
event title 2  2012/08/15 

這裏就是我試圖做的,但我通過

得到的順序錯誤
SELECT posts.postsID, posts.postsSubject FROM posts where posts.postsCategory = 1 ORDER BY posts.postsTimestamp DESC 
UNION 
SELECT events.eventsID, events.eventsTitle FROM events where events.eventsLocation = 1 ORDER BY events.eventsTimestamp DESC 

回答

1

你只需要一個ORDER BY條款,到了最後,經過2種聯合在一起選擇:

SELECT postsID   AS id, 
     postsSubject  AS title, 
     postsTimestamp AS timestamp 
FROM posts 
WHERE postsCategory = 1 

UNION 

SELECT eventsID, 
     eventsTitle, 
     eventsTimestamp 
FROM events 
WHERE eventsLocation = 1 

ORDER BY timestamp DESC ; 
+0

事件部分的select語句是否需要將eventsTimestamp作爲某個事件來處理? – user1406951

+0

不,第二個SELECT列表不需要別名。使用第一個SELECT列表中的那些列表。 –

+0

謝謝你工作完美! – user1406951

1

試試這個,

SELECT Title, `TimeStamp` 
(
    SELECT posts.postsID as ID, 
      posts.postsSubject as Title, 
      eventsTimestamp as `TimeStamp` 
    FROM posts 
    where posts.postsCategory = 1 
    UNION 
    SELECT events.eventsID as ID, 
      events.eventsTitle as Title, 
      postsTimestamp as `TimeStamp` 
    FROM events 
    where events.eventsLocation = 1 
) x 
ORDER BY `TimeStamp` DESC 
2

由於UNION Syntax中提到:

要使用ORDER BYLIMIT子句對整個進行排序或限制結果,將單個SELECT語句括起來,並在最後一個之後放置ORDER BYLIMIT。下面的示例使用這兩種條款:

(SELECT a FROM t1 WHERE a=10 AND B=1) 
UNION 
(SELECT a FROM t2 WHERE a=11 AND B=2) 
ORDER BY a LIMIT 10;

因此:

(SELECT postsSubject AS title, postsTimestamp AS timestamp 
    FROM posts 
    WHERE postsCategory = 1) 

UNION ALL 

(SELECT eventsTitle, eventsTimestamp 
    FROM events 
    WHERE eventsLocation = 1) 

ORDER BY timestamp DESC 

看到它的sqlfiddle

+0

執行查詢後,有沒有辦法區分post和event?例如,一個是event.php?id = 1,另一個可能是post.php?id = 1 – user1104854

+0

@ user1104854:是的,您可以在每個「SELECT」中包含一個新列 - 例如'(SELECT'post'AS type,postsSubject ...)UNION ALL(SELECT'event',eventsTitle ...)ORDER BY timestamp DESC'。 – eggyal