Hello, there is a normal code

$result = mysql_query("SELECT * FORM catalog order by id"); foreach($result as $item) { echo $item['id']; echo $item['name']; } 

Sorted by Id. How to make sorting what first there would be those points in which id is equal 5,6,7 and then all the others?

    4 answers 4

     SELECT * FROM <table_name> WHERE (ID>=5) AND (ID<=7) UNION SELECT * FROM <table_name> WHERE (ID<5) UNION SELECT * FROM <table_name> WHERE (ID>7) 

    Then everything is even simpler:

     SELECT * FROM <table_name> WHERE ID IN (5,6,7) UNION SELECT * FROM <table_name> WHERE ID IN NOT (5,6,7) 
    • Interesting, but Id can go out of turn 5,6,7 and for example 4,13,18 - dogmar
    • And nothing affects this =) The query works like this:> 1) First, it searches for all records with ID = 5, ID = 6 and ID = 7> 2) Then it merges with another query, which in> turn displays all records with ID <5> 3) And finally, plus one more join with a query that> displays all records with ID> 7 - AseN
    • I understood how the query works :) if the ID goes 4,13,18 and dragging out all the records from 4 to 18 will not be the right decision, since flies those id which should not be in the beginning. - dogmar
    • You write:> How to do a sorting so that the items in which id> is equal to 5.6.7 first go to - AseN
    • Yes, but then in practice I realized that the necessary IDs could be in a different order, sorry :) - dogmar

    Try this:

     SELECT * FROM <table_name> WHERE ID IN (1,5,7) UNION SELECT * FROM <table_name> WHERE ID NOT IN (1,5,7) 
    • also try SELECT * FROM <table_name> ORDER BY FIELD (ID, 1,5,7) - Vitalii Maslianok
     $result = mysql_query("SELECT * FORM `catalog` WHERE `id` > 5 order by id"); 
    • It turns out all that more than 5 goes first. and I need that to be so 5,6,7,1,2,3,4,8,9 - dogmar
    • it is necessary to glue =) - Gorets
    • where is it)? - dogmar
    • $ result = mysql_query ("SELECT * FORM catalog WHERE id IN (5,6,7,1,2,3,4,8,9)"); - johniek_comp
    • Well, I have not only 9 fields, 9 fields for example. fields can be and 1000 - dogmar

    The task is not relevant. If you need to be able to sort in a random order - make a separate field in the table and sort by it. And in this field already set the values ​​you need.

    and if you still want to pervert:

     ORDER BY id>4, id < 8, id 

    ps: I did not check, but it should work