2016-06-13 53 views
1

這是我的實際查詢:MySQL的ORDER BY第一場那麼第二場

SELECT DISTINCT eventi.img AS img, posizione AS pos 
    FROM eventi 
    WHERE homepage =1 
    UNION 
    SELECT DISTINCT prodotti.img, prodotti.posizione 
    FROM prodotti 
    WHERE homepage =1 
    ORDER BY pos ASC 

返回,如 「1,1,2,2」 的位置。我希望它按字段返回位置,如「事件位置1,2 - >產品位置1,2」。現在它是混合事件和產品職位...

回答

2

你可以這樣說:

SELECT t.img,t.pos FROM (
    SELECT DISTINCT 1 as order_col, eventi.img AS img, posizione AS pos 
    FROM eventi 
    WHERE homepage =1 
    UNION 
    SELECT DISTINCT 2 , prodotti.img, prodotti.posizione 
    FROM prodotti 
    WHERE homepage =1) t 
ORDER BY t.order_col,t.pos 

如果你不關心選擇order_col則可以避開子選擇,並通過內放的順序。

+0

工作,謝謝 – Tony33

0

根據docs,你有一個聯盟,你需要採取額外的步驟,以確保該聯盟的最後查詢中的order by子句適用於所有查詢,而不僅僅是最後的查詢:

SELECT ... 
UNION 
SELECT ... ORDER  <--order final query only 

VS

(SELECT ...) 
UNION 
(SELECT ...) ORDER  <--order all queries as a single set 

注意額外()

+0

用'(SELECT DISTINCT eventi.img AS IMG,eventi.posizione AS POS FROM EVENTI WHERE主頁= 1個ORDER BY POS ASC) UNION (SELECT DISTINCT prodotti.img,prodotti.posizione AS POS2 FROM PRODOTTI 在哪裏主頁= 1 ORDER BY pos2 ASC)'我現在得到1-2-2-1 ... – Tony33