HELP HELP - 4 months ago 38
SQL Question

MySQL ORDER BY question

How can I add an order by

users_friends.date_created
that governs both select queries.

Here is my MySQL code.

(SELECT A.user_id, A.friend_id, B.username, B.avatar
FROM users_friends AS A
INNER JOIN users AS B
ON A.friend_id = B.user_id
AND A.user_id = 3
AND A.friendship_status = 1)
UNION
(SELECT A.friend_id, A.user_id, B.username, B.avatar
FROM users_friends AS A
INNER JOIN users AS B
ON B.user_id = A.user_id
AND A.friend_id = 3
AND A.friendship_status = 1)
LIMIT 10

Answer

You can add an outer select with an order by and wrap the union as a derived table

SELECT user_id, friend_id, username, avatar FROM (
(SELECT A.user_id, A.friend_id, B.username, B.avatar
FROM  users_friends AS A 
INNER JOIN users AS B 
ON A.friend_id = B.user_id 
AND A.user_id = 3 
AND A.friendship_status = 1)
UNION
(SELECT A.friend_id, A.user_id, B.username, B.avatar
FROM users_friends AS A 
INNER JOIN users AS B 
ON B.user_id = A.user_id 
AND A.friend_id = 3 
AND A.friendship_status = 1)
LIMIT 10
) C
ORDER BY avatar
Comments