【问题标题】:Where to put the ORDER BY in this union statement?在这个联合声明中将 ORDER BY 放在哪里?
【发布时间】:2015-07-19 13:31:51
【问题描述】:

我的工会声明似乎有效:

SELECT q.id, q.hits, q.type, q.title, q.date, q.author, q.wfurl
FROM (SELECT id AS id, hits AS hits, type AS type, title AS title, date AS date, author AS author, wfurl AS wfurl, status AS status
FROM articles WHERE status = 1
UNION SELECT id, hits, type, title, published, author_id, url, status
FROM new_articles WHERE status = 1) AS q
GROUP BY q.id

我正在尝试按ORDER BY type 的类型订购整个东西,但无论我把它放在哪里似乎都会引发错误。我把它放在第一行,在 AS 之后和两个选择里面,没有运气。

【问题讨论】:

    标签: mysql sql sql-order-by union


    【解决方案1】:

    order by 会跟在group by 之后:

    SELECT q.id, q.hits, q.type, q.title, q.date, q.author, q.wfurl
    FROM ((SELECT id AS id, hits AS hits, type AS type, title AS title, date AS date, author AS author, wfurl AS wfurl, status AS status
           FROM articles
           WHERE status = 1
          ) UNION
          (SELECT id, hits, type, title, published, author_id, url, status
           FROM new_articles 
           WHERE status = 1
          )) q
    GROUP BY q.id
    ORDER BY type;
    

    如果您知道这两个表没有重复,那么您应该使用UNION ALL 而不是UNIONUNION 通过删除重复项会产生开销。分配与名称相同的表别名也是多余的,因此hits as hits 是不必要的(等等)。

    编辑:

    如果您想要一个高效的查询,以下可能会更快,并且可能会满足您的需求:

    select a.*
    from articles a
    where status = 1
    union all
    select na.*
    from new_articles na
    where status = 1 and
          not exists (select 1 from articles a where a.id = na.id)
    order by type;
    

    这消除了union 的开销。如果两个表中都存在id,则它会从第一个表中获取值(您可以颠倒逻辑顺序以从第二个表中获取值)。唯一真正的开销是末尾的 order by,而您的版本有 uniongroup byorder by 的开销。

    【讨论】:

    • 呃,我在下面尝试 ORDER BY q.type,谢谢 :p
    • 如果您只想要几列,坚持单独的工会会更好吗?我从中选择的这些表中有很多东西,这只是几列
    猜你喜欢
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多