Search code examples
phpmysqlsqlsymfony1propel

Sort WHERE IN SQL


Possible Duplicate:
mysql custom sort

I have an array of IDs:

$ids = array(5, 1, 4, 2, 3);

and I make a query:

SELECT * FROM Persons
WHERE id IN $ids

and I receive this object:

1, 2, 3, 4, 5

Is it possible to sort this same as in array? I would like receive

5, 1, 4, 2, 3.

I also use PROPEL. Maybe with Propel ORM in Symfony, is this possible?


Solution

  • in mysql you can use the field function for custom sort order. For example:

    $ids = array(5, 1, 4, 2, 3);
    $ids = implode(',', $ids);
    $sql = "SELECT * FROM Persons
            WHERE id IN ($ids)
            ORDER BY FIELD(id, $ids)";