1

我正在尝试使用联合从不同的表中选择项目,按日期排序(最新的优先)

说我有以下表格

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
4

3 回答 3

2

UNION语法下所述:

要使用ORDER BYorLIMIT子句对整个UNION结果进行排序或限制,请将各个SELECT语句括起来并将ORDER BYorLIMIT放在最后一个语句之后。以下示例同时使用了这两个子句:

(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上查看。

于 2012-08-27T01:30:08.377 回答
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
于 2012-08-27T01:23:43.867 回答
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 ;
于 2012-08-27T01:24:28.657 回答