【问题标题】:Sort WHERE IN SQL [duplicate]在 SQL 中排序 [重复]
【发布时间】:2012-06-29 06:13:33
【问题描述】:

可能重复:
mysql custom sort

我有一个 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,这可能吗?

【问题讨论】:

  • 一种解决方案是在 foreach 循环中运行查询
  • @cristi_b:我认为运行一个查询比运行多个查询要好。
  • 你是对的,忘了usort

标签: php mysql sql symfony1 propel


【解决方案1】:

在 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。酷。
【解决方案2】:

您可以在运行查询后在 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;
});

【讨论】:

    猜你喜欢
    • 2018-08-14
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    • 2019-07-18
    • 2016-04-01
    • 2014-10-19
    • 1970-01-01
    相关资源
    最近更新 更多