【问题标题】:MySQL SELECT in order of array valuesMySQL SELECT 按数组值的顺序
【发布时间】:2021-04-20 15:31:41
【问题描述】:

谁能帮我查询查询?

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

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

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

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

谢谢大家!

【问题讨论】:

  • 表格中的其他列是否代表您想要的顺序?您必须在 SQL 中提供 ORDER BY 才能获得确定的行顺序,但是根据您的整数顺序将这样的子句组合在一起是一团糟。如果您无法创建ORDER BY,则需要在准备输出时在 PHP 代码中修改结果集数组。
  • 不,恐怕没有其他专栏了!

标签: php mysql select where-clause


【解决方案1】:

如果表中没有另一列用于在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 的大小为数千,则此方法效率不高,因为它需要在写出之前获取所有行,但您似乎正在处理较小的数组。

【讨论】:

    猜你喜欢
    • 2011-01-12
    • 2017-01-06
    • 2011-06-08
    • 1970-01-01
    • 2011-12-24
    • 2017-02-11
    • 2020-11-21
    • 1970-01-01
    • 2011-06-20
    相关资源
    最近更新 更多