MySQL SELECT 数组值的顺序

MySQL SELECT in order of array values

有谁能帮我查询一下吗?

我有一个 ID 数组 $IDvalues = array("128", "159", "7", "81", "82", "83");

并且需要按照数组的顺序从另一个table中获取数据。目前,我有这个查询:

$detailsQuery = mysqli_query($conn, "SELECT details FROM detailsTable WHERE id IN (".implode(',', $IDvalues).")");

但它是按数字顺序获取的 (7, 81, 82, 83, 128, 159)。我先需要 128,然后是 159...我可以在查询中使用什么来保留订单吗?

谢谢大家!

如果 table 中没有另一列用于在 ORDER BY 中进行排序,您将无法从 SQL 查询返回确定的排序顺序。 可以使用像

这样精心设计的链来编造一个 ORDER BY
ORDER BY 
CASE
  WHEN id = 128 THEN 1
  WHEN id = 159 THEN 2
 ....
END

但这是个糟糕的主意。

相反,我建议将获取的行存储在由其 id 列索引的数组中,然后使用原始 $IDvalues 数组对其进行迭代:

// Empty array to hold your result rows
$rows = [];
while ($row = mysqli_fetch_assoc($detailsQuery)) {
  // Append the fetched row to your result array using its id as index
  $rows[$row['id']] = $row;
}

// Output your rows using the original $IDvalues
// to lookup rows by index.
// Looping over $IDvalues ensures you get its order
// back out.
foreach ($IDvalues as $id) {
  // Retrieve from your $rows array by id index
  // Output them however you need
  print_r($rows[$id]);
}

如果 $IDvalues 的大小为数千,则此方法效率不高,因为它需要在写出所有行之前获取所有行,但看起来你正在处理一个较小的数组。