2010-08-27 55 views
0
SELECT 
.... 
GROUP BY 
c.city_id 

ORDER BY p.name desc 
UNION 
SELECT 
... 

GROUP BY 
c.city_id, p 

ERROR 1221(HY000):UNION和秩序的不正確的使用情況有什麼不對這種格式

有沒有辦法,因爲我想上查詢到有一個排序依據,我需要有這樣的格式通過底部查詢獲得相同的訂單

回答

3

在ORDER BY正值年底

select * 
from.. 
union all 
select * 
from... 
order by.... 

如果你想第一個查詢,首先出現你所能做的就是這個

select *, 1 as SortOrder 
from.. 
union all 
select * ,2 as SortOrder 
from... 
order by SortOrder,<other columns>... 
1

ORDER BY應位於SELECT語句的末尾,而不是在UNION之前。

有關UNION語法的更多信息,請參見herehere

1

無法通過使用命令將由UNION加入的選擇查詢。如果您願意,可以選擇之後的所有內容,然後添加訂單。

+0

非*加入*由工會*合併* – 2010-08-27 16:06:55

1

在標準SQL中,ORDER BY出現在UNION查詢的末尾,並應用於這些查詢的最終結果。

...
MySQL允許你,如果你括在括號中使用ORDER BY UNION語句中:

( SELECT .... 
    FROM ... 
GROUP BY c.city_id 
ORDER BY p.name DESC) 
UNION 
    SELECT ... 
    FROM ... 
GROUP BY c.city_id 

...還which'll允許您使用LIMIT。 ..

0

至於其他的答案說,它被解析爲

SELECT { unordered_stuff UNION SELECT unordered_stuff } ORDER BY foo 

有些人,雖然我不相信所有人,但數據庫support an alternate disambigiouation syntax。這是來自Pg列表。

(SELECT * from foo where priority = 1 order by seniority) 
UNION ALL 
(select * from foo where priority > 1 order by seniority, priority) 

Otherwise the ORDER BY is considered to apply to the whole UNION result 
(it's effectively got lower binding priority than the UNION). Note also 
that you *must* use UNION ALL, else UNION will attempt to eliminate 
duplicates, and mess up the sort order while at it. 

See also Bruno's solution nearby. Not sure which of these approaches 
would be faster; try both.