Jose Fontanilla
Jose Fontanilla

Reputation: 13

Order in mysql query

I would just like to ask about a problem that I have with my query/queries. For example I have the following result from a query which is a union of 4 queries:

alpha,alpha,alpha,bravo,bravo,bravo,charlie,charlie,charlie,delta,delta,delta

what do I need to do to have the order of the result to:

alpha, bravo, charlie, delta, alpha, bravo, charlie, delta, alpha, bravo, charlie, delta?

I apologize if this question might have already been answered before here in stackoverflow as I don't know the proper keywords for this problem for me to search the database. Any help would be very much appreciated, thanks!

Upvotes: 1

Views: 103

Answers (3)

user903772
user903772

Reputation: 1562

You Can use the distinct keyword:

Select DISTINCT

Upvotes: 0

Michel Feldheim
Michel Feldheim

Reputation: 18250

MySQL can either order numerically (1>2>n) or alphabetically (a>b>x). How data is ordered depends on the type to order.

Mahmouds answer is creating a numerical field you can order the union by.

Upvotes: 0

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79909

You can have a new column something like a sortorder:

SELECT *
FROM
(
   SELECT acolumn, 1 AS sortorder FROM table1
   UNION ALL
   SELECT acolumn, 2              FROM table2
   UNION ALL
   SELECT acolumn, 3              FROM table3
   UNION ALL
   SELECT acolumn, 4              FROM table4
) u
ORDER BY aColumn, sortorder;

Upvotes: 4

Related Questions