使用2个表中的字段对UNION进行排序

时间:2011-06-22 19:25:42

标签: mysql union

我正在尝试从表NEWS和EVENTS中选择即将发生的事件和最新消息,并按NEWS.timestamp和EVENT.datetime订购

基本的非有序查询如下:

SELECT event_id, title FROM events
UNION
SELECT news_id, subject FROM news

2 个答案:

答案 0 :(得分:2)

将每个列添加到您的选择列表中,每个列的名称别名相同。然后只在底部ORDER BY

SELECT
  event_id,
  title,
  datetime AS thedate
FROM events
UNION
SELECT
  news_id,
  subject,
  timestamp AS thedate
FROM news
ORDER BY thedate

答案 1 :(得分:1)

迈克尔答案的一个小变化(如果您想按时间戳和日期时间排序但不显示它们):

  SELECT
    event_id,
    title
  FROM 
    ( SELECT
        event_id,
        title,
        datetime AS thedate
      FROM events
    UNION ALL
      SELECT
        news_id,
        subject,
        timestamp AS thedate
      FROM news
    ) AS tmp
  ORDER BY thedate