How to bring a specific result from one SQL query above the others?

1

I have the following SQL query:

SELECT DISTINCT 'user_id' AS 'id', 'user_name' AS 'name' FROM 'users' ORDER BY 'id' ASC;

That generates output:

+----+--------+
| id | name   |
+----+--------+
|  1 | Calebe |
|  2 | João   |
|  3 | Lucas  |
|  4 | Pedro  |
+----+--------+

However, I need determined user to come in the results, before the others. Example : I want user_id = 3 to appear at the top. Then the result should come as follows:

+----+--------+
| id | name   |
+----+--------+
|  3 | Lucas  |
|  1 | Calebe |
|  2 | João   |
|  4 | Pedro  |
+----+--------+

How can I do this?

    
asked by anonymous 03.02.2014 / 00:24

4 answers

4

For your specific query, something like this works:

SELECT DISTINCT 'user_id' AS 'id', 'user_name' AS 'name' FROM 'users' 
ORDER BY 'id' = 3 DESC, 'id' ASC;

In this way, it is guaranteed that the first ordering term obeys the desired ID.

    
03.02.2014 / 00:37
0
SELECT DISTINCT 'user_id' AS 'id', 'user_name' AS 'name', if(user_name = 'Lucas',0,1) as 'ordem' FROM 'users' ORDER BY 'ordem' ASC, 'id' ASC;
    
03.02.2014 / 00:37
0

There is a solution here: link

ORDER BY (user_id.id=3) ...
    
03.02.2014 / 00:39
0

You can also use an order by field and desired values, using the following rule:


SELECT DISTINCT 'user_id' AS 'id', 'user_name' AS 'name' FROM 'users' 
ORDER BY FIELD (id, 3, 1, 2, 4 ) ASC, id DESC;

    
29.06.2015 / 16:08