I have the following MySQL statement that returns a list of user_id's
SELECT user_id FROM user_links WHERE linked_user_id='1234'
The user_id
never contains the linked_user_id
that I use in the where
clause. So I want to always add the from clause "linked_user_id" in the result but also want to sort by the user_id ASC.
Is there a way to do this in the MySQL statement itself or do I have to do this with some other scripting?
CodePudding user response:
Use UNION
SELECT user_id FROM user_links WHERE linked_user_id='1234'
UNION ALL
SELECT '1234'
CodePudding user response:
You can modify your condition to add that user_id
:
SELECT user_id FROM user_links WHERE '1234' in (user_id, linked_user_id)
Let's sort it accordingly:
SELECT user_id
FROM user_links
WHERE '1234' in (user_id, linked_user_id)
ORDER BY user_id
Or you can even guarantee that the linked user id will be the last row by:
SELECT user_id
FROM user_links
WHERE '1234' in (user_id, linked_user_id)
ORDER BY user_id = '1234', user_id