谁能帮我查询查询?
我有一个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个……我可以在查询中使用什么来保留订单吗?
谢谢!
如果表中没有要在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
的大小是数千,这种方法将不是有效的,因为它需要在将它们写出来之前获取所有行,但看起来您正在处理一个较小的数组。