将 ORDER BY 放在这个 union 语句的什么地方?
Where to put the ORDER BY in this union statement?
我得到了这个似乎有效的联合声明:
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 之后和两个 selects 里面,没有运气。
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;
如果你知道两个table没有重复,那么你应该使用UNION ALL
而不是UNION
。 UNION
删除重复项会产生开销。分配与名称相同的 table 别名也是多余的,因此 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
出现在两个 table 中,它会从第一个中获取值(您可以颠倒逻辑顺序以从第二个中获取值)。唯一真正的开销是最后的 order by
,而您的版本有 union
、group by
和 order 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) AS q
GROUP BY q.id
而且我正尝试按类型对所有内容进行排序,因此 ORDER BY type
但是无论我将其放入何处似乎都会引发错误。我把它放在第一行,在 AS 之后和两个 selects 里面,没有运气。
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;
如果你知道两个table没有重复,那么你应该使用UNION ALL
而不是UNION
。 UNION
删除重复项会产生开销。分配与名称相同的 table 别名也是多余的,因此 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
出现在两个 table 中,它会从第一个中获取值(您可以颠倒逻辑顺序以从第二个中获取值)。唯一真正的开销是最后的 order by
,而您的版本有 union
、group by
和 order by
.