2015-07-19 41 views
0

我有了這個聯盟聲明,似乎是工作:將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之後和兩次選擇中都沒有運氣。

回答

2

order bygroup 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而不是UNION。通過刪除重複項,UNION會產生開銷。分配與名稱相同的表別名也是多餘的,因此不需要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,而您的版本的開銷爲union,group byorder by

+0

uhh我正在嘗試在q.type下面,謝謝:p – Crizly

+0

如果你只想要幾列,堅持單個工會會更好嗎?這些表格選擇有很多東西在他們這只是幾列 – Crizly