我的代码:
$afer_result = mysql_query("SELECT * FROM aq_afers WHERE aferId = '".$afer_id."'");
while ($afer = mysql_fetch_array($afer_result)) {
$item_result = mysql_query("SELECT * FROM aq_".$afer['ItemCategory']."s WHERE ItemId = '".$afer['ItemId']."' ORDER BY ItemLevel");
$item = mysql_fetch_assoc($item_result);
echo $item['ItemLevel'];
echo "\n";
}
我希望输出是一个从最低到最高排序的数字列表,但这就是我的输出:
10
37
62
15
35
55
75
95
105
70
40
50
15
35
1
55
知道为什么 ORDER BY
没有像我预期的那样工作吗?
最佳答案
您的代码的问题是您在循环内运行多个查询。每个查询的结果都是有序的,但全局结果不是有序的。
解决方案是使用循环构建 UNION sql 查询。您可以在循环外运行查询; UNION 查询的 ORDER BY 子句全局应用于其结果。当然,这假设所有查询返回相同的列(否则您需要调整代码)。
代码;
$afer_result = mysql_query(
"SELECT *
FROM aq_afers
WHERE aferId = '".$afer_id."'"
);
$sql_parts = array();
while ($afer = mysql_fetch_array($afer_result)) {
array_push(
$sql_parts,
"SELECT *
FROM aq_".$afer['ItemCategory']."s
WHERE ItemId = '".$afer['ItemId']."'"
);
}
$sql = join(' UNION ALL ', $sql_parts);
$item_result = mysql_query($sql . 'ORDER BY ItemLevel');
while ($item = mysql_fetch_array($item_result)) {
echo $item['ItemLevel'];
echo "\n";
}
关于php - ORDER BY 在 PHP/MySQL 中未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53981221/