在这个联合声明中放置ORDER BY的位置?

时间:2015-07-19 13:31:52

标签: mysql sql sql-order-by union

我已经得到了这个似乎有效的联合声明:

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之后和两个选择内部没有运气。

1 个答案:

答案 0 :(得分:2)

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的开销。