MySQL Forums
Forum List  »  InnoDB

Re: ORDER BY ignored in UNION
Posted by: Paul Whipp
Date: January 06, 2009 09:31PM

In case anyone else finds this topic long after the event :-
Internal ORDER BY clauses are ignored.

Not recommended for large results but you can add a field to the union specifically for ordering to avoid the need for unnecessary decoration on your desired values. Here is a real example where a client wanted a few 'special' options at the top of a list with just the remainder of the list in alphabetical name order:

(SELECT
CONCAT(id,",0") as "value",
name as "label",
CONCAT("AAAAAA",name) as ordering
FROM
pp_locations
WHERE
pp_locations.id NOT IN (2, 3, 4))
UNION
(SELECT CONCAT("4,",pp_customers.home_address_id) as "value",
CONCAT("Home of ",pp_customers.firstname," ",pp_customers.lastname) as "label",
"AAAAAB" as ordering
FROM
pp_customers
JOIN pp_orders ON pp_customers.user_id = pp_orders.customer_id
WHERE
pp_orders.id = 2)
UNION
(SELECT
CONCAT("2,",id) as "value",
name as "label",
CONCAT("AAAAAC",name) as ordering
FROM
pp_special_locations)
UNION
(SELECT
CONCAT("3,",id) as "value",
name as "label",
CONCAT("AAAAAD",name) as ordering
FROM
pp_vets
WHERE
is_agency = 1)
ORDER BY ordering;

Pretty nasty but it got the job done.

Options: ReplyQuote


Subject
Views
Written By
Posted
19802
March 15, 2007 03:19AM
8901
March 15, 2007 05:19PM
7906
March 16, 2007 05:49AM
7725
March 19, 2007 11:27AM
Re: ORDER BY ignored in UNION
6936
January 06, 2009 09:31PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.