Question

I have mySQL DB where I have this: link
I need to return result where first item will be item with id==1 and then add to that everything else in alphabetical order. This is what I want:
[Názov predmetu], [Algoritmizácia úloh], [Fyzika 1]...

Now Im using this:

<?php
    $result = mysql_query("SELECT nazov FROM tbPredmety ORDER BY nazov ASC");
    echo "<select name='subject_name'>";

    while ($row = mysql_fetch_assoc($result))
    {
        echo "<option value = '" . $row[nazov] . "'>" . $row[nazov] . "</option>";
    }

    echo "</select>";
?>
Was it helpful?

Solution

You can add a CASE clause inside your ORDER BY clause:

SELECT nazov 

FROM tbPredmety 

ORDER BY 
   -- item(s) with item_id 1 will appear first 
   CASE WHEN item_id = 1 THEN 0 ELSE 1 END, 
   nazov ASC

I used THEN 0 ELSE 1 but for your purpose you could use any pair of values in which the former value is considered less than the latter value when sorting.

EDIT: For mysql you may need to use CASE ... END CASE. If the above does not work try changing END to END CASE.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top