apply "ORDER BY" on a "UNION" (Mysql)

Quiche picture Quiche · May 2, 2017 · Viewed 16.8k times · Source

Good Day. So, everythign is in the title :)

I am looking to merge the result of two requests and order the result together (as in not one after the other). => I was thinking of applying an union and order them. It didn't worked.

I looked around like here on Stack or here developpez (!!french website). I try the different exemple, and suggestion, but no success. It seems from what i red that it's because I am working on Mysql.

Anyway, here are my attemps, and the results:

My original 2 requests

SELECT * FROM user_relation WHERE from_user_id = 1
List item
SELECT * FROM user_relation WHERE to_user_id = 1

this result of a list made of the result of teh frist select (odered by index key) followed by the result of 2nd select ordered by Index KEy.

Attempt 1:

(SELECT * FROM user_relation WHERE from_user_id = 1 ORDER BY trust_degree)
UNION
(SELECT * FROM user_relation WHERE to_user_id = 1 ORDER BY trust_degree)

The request ran, but teh result were teh same as orginal request: result of first select (order by index Key) followed by the results of the second request

Attempt 2:

(SELECT * FROM user_relation WHERE from_user_id = 1 ORDER BY trust_degree)
UNION
(SELECT * FROM user_relation WHERE to_user_id = 1 ORDER BY trust_degree)
ORDER BY trust_degree

=> request ran, result as attempt 1, but with a warning i the Mysql logic: (this type of close has been already analyzed (ORDER BY))

Attempt 3

(SELECT * FROM user_relation WHERE from_user_id = 1
UNION
SELECT * FROM user_relation WHERE to_user_id = 1)
ORDER BY trust_degree

=> Do not ran, but an error #1064 - syntax error near UNION

Attempt 4:

SELECT *
FROM (
(SELECT * FROM user_relation WHERE from_user_id = 1)
UNION
(SELECT * FROM user_relation WHERE to_user_id = 1)
)
ORDER BY trust_degree 

=> do not ran, and a nice list of 6 error. Any suggestion?

Answer

Michael Kunst picture Michael Kunst · May 2, 2017
SELECT *
FROM (
(SELECT * FROM user_relation WHERE from_user_id = 1)
UNION
(SELECT * FROM user_relation WHERE to_user_id = 1)
) AS i
ORDER BY trust_degree

You have to assign an alias to your select. But in this case a UNION is not necessary and could be replaced by a simple OR, as @Karoly Horvath points out in his comment. The resulting query would look like this:

SELECT 
 * 
FROM user_relation 
WHERE from_user_id = 1 OR to_user_id = 1 
ORDER BY trust_degree