【问题标题】:union select and order by with mysql使用mysql联合选择和排序
【发布时间】:2012-08-27 01:19:16
【问题描述】:

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

假设我有以下表格

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

这是我正在尝试做的事情,但我从 order by 中得到一个错误

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

【问题讨论】:

    标签: mysql sql-order-by union


    【解决方案1】:

    UNION Syntax下所述:

    要使用ORDER BYLIMIT 子句对整个UNION 结果进行排序或限制,请将各个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 上查看。

    【讨论】:

    • 查询执行后有没有办法区分post和event?例如一个是 event.php?id=1 而另一个可能是 post.php?id=1
    • @user1104854:是的,您可以在每个 SELECT 中包含一个新列 - 例如(SELECT 'post' AS type, postsSubject ...) UNION ALL (SELECT 'event', eventsTitle ...) ORDER BY timestamp DESC.
    【解决方案2】:

    您只需要一个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 ;
    

    【讨论】:

    • 事件部分的选择语句是否需要将 eventsTimestamp 定义为某种东西?
    • 不,第二个 SELECT 列表不需要别名。使用第一个 SELECT 列表中的那些。
    • 假设我想添加另一个表(我们称之为tableB)。我是否只需在事件选择语句之后添加 tableB 而不用 AS 语句修改帖子部分中的任何内容?
    【解决方案3】:

    试试这个,

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-14
      • 2012-08-25
      • 2010-12-25
      相关资源
      最近更新 更多