MySQL ORDER Task

I have a fairly simple SQL query, but something is missing, and I have not yet found an answer to this problem. The thing is, I select multiple fields with multiple identifiers, and I want the result to be ordered in this particular order.

The request is as follows

SELECT `content`.* 
FROM   `content` 
WHERE  (user_id = "1" AND ( id = "4" OR id = "7" OR id = "5" OR id = "8" )) 

The default is "id ASC" (id is my primary key), but I want the order to be 4,7,5,8 in this particular case.

Any ideas?

+3
source share
5 answers

This will do what you want:

select * 
from myTable
order by field(myID, 8, 7, 6) desc;

You can set the order of any identifier (or other) that should appear, and after that the rest will follow. Hope this helps.

@http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_field

+5
ORDER BY CASE user_id  
    WHEN "4" THEN 1  
    WHEN "7" THEN 2  
    WHEN "5" THEN 3  
    WHEN "8" THEN 4  
    ELSE 5  
END

, - "user_id" "order_by_val", "ORDER BY order_by_val".


EDIT: Per @Tim, MySQL - FIELD() - , , , .
+10

, case:

order by case id
             when "4" then 1
             when "7" then 2
             when "5" then 3
             when "8" then 4
             else 99
         end

, mysql, .

+3
ORDER BY CASE id WHEN 4 THEN 1 
                 WHEN 7 THEN 2 
                 WHEN 5 THEN 3 
                 WHEN 8 THEN 4 
                 ELSE 99
         END; 
+1

.

ORDER BY CASE ID WHEN 4 THEN 1 WHEN 7 THEN 2 WHEN 5 THEN 3 WHEN 8 THEN 4 ELSE 5 END 
0

Source: https://habr.com/ru/post/1705276/


All Articles