这种格式有什么问题

时间:2010-08-27 16:02:36

标签: mysql sql

SELECT 
....
GROUP BY 
c.city_id

ORDER BY p.name desc
UNION 
SELECT 
...

GROUP BY 
c.city_id, p

ERROR 1221(HY000):UNION和ORDER BY的使用不正确

有没有办法让这种格式,因为我希望顶部查询有一个orderby我需要在底部查询具有相同的orderby

5 个答案:

答案 0 :(得分: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 :(得分:1)

ORDER BY应该在你的select语句的末尾,而不是在UNION之前。

有关UNION语法的详细信息,请参阅herehere

答案 2 :(得分:1)

您不能对将由UNION加入的选择查询使用订单。如果需要,您可以随后选择所有内容并在此之后添加订单。

答案 3 :(得分:1)

在标准SQL中,ORDER BY出现在UNION'd查询的末尾,并应用于这些查询的最终结果。

的...
MySQL允许您在UNION语句中使用ORDER BY,如果将其括在括号中:

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

...这也允许你使用LIMIT ...

答案 4 :(得分: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.