我正在尝试使用工会从不同的表中选择项目,按日期排序(最新的第一个)
说我有以下表格
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
答案 0 :(得分:2)
正如UNION
Syntax所述:
要使用
ORDER BY
或LIMIT
子句对整个UNION
结果进行排序或限制,请为各个SELECT
语句添加括号并放置ORDER BY
或{ {1}}在最后一个之后。以下示例使用两个子句:LIMIT
因此:
(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;
在sqlfiddle上查看。
答案 1 :(得分: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 :(得分: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 ;