可能重複:
mysql custom sort排序凡在SQL
我有一組ID:
$ids = array(5, 1, 4, 2, 3);
和我進行查詢:
SELECT * FROM Persons
WHERE id IN $ids
和我收到此目的:
1,2,3,4,5
是否有可能進行排序此相同數組?我想接收
5,1,4,2,3
我也使用PROPEL。也許在Symfony中使用Propel ORM,這可能嗎?
可能重複:
mysql custom sort排序凡在SQL
我有一組ID:
$ids = array(5, 1, 4, 2, 3);
和我進行查詢:
SELECT * FROM Persons
WHERE id IN $ids
和我收到此目的:
1,2,3,4,5
是否有可能進行排序此相同數組?我想接收
5,1,4,2,3
我也使用PROPEL。也許在Symfony中使用Propel ORM,這可能嗎?
在MySQL中,你可以使用field function自定義排序次序。例如:
$ids = array(5, 1, 4, 2, 3);
$ids = implode(',', $ids);
$sql = "SELECT * FROM Persons
WHERE id IN ($ids)
ORDER BY FIELD(id, $ids)";
我不知道'FIELD'。涼。 –
運行查詢後,可以使用PHP對它進行排序。
像這樣的東西(PHP 5.3+只):
$ids = array(5, 1, 4, 2, 3);
// Run Query...
// assume $results is the result array
usort($results, function($a, $b) use($ids){
$a = array_search($a['id'], $ids);
$b = array_search($b['id'], $ids);
return $a -$b;
});
一個解決方案是在foreach循環中運行查詢 –
@cristi_b:我認爲運行一個查詢比多個查詢更好。 –
你是對的,忘記了usort –