在php/mysql中按未按预期工作排序

50few1ms  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(347)

我的代码:

$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 不是像我期望的那样工作吗?

bvjveswy

bvjveswy1#

代码的问题是在一个循环中运行多个查询。每个查询的结果都是有序的,而不是全局结果。
一种解决方案是使用循环来构建unionsql查询。您可以在循环外运行查询;联合查询的ORDERBY子句全局应用于其结果。当然,这假设所有查询都返回相同的列(否则需要修改代码)。
代码;

$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";
}
fwzugrvs

fwzugrvs2#

您的代码选择类别并遍历每个类别。它为排序的每个类别选择itemlever,但不是同时选择所有类别。第一类10、37、62第二类15、35、55、75、95、105第三类70等。
因此,应该将两个sql查询合并为一个,并对结果进行排序。
如果不可能,您应该将itemlevels存储到一个数组中,并在打印它们之前对其进行排序。

$afer_result = mysql_query("SELECT * FROM aq_afers WHERE aferId = '".$afer_id."'");
$itemLevels = [];
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);
    $itemLevels[] = $item['ItemLevel'];
}
asort($itemLevels);
foreach ($itemLevels as $itemLevel) {
    echo $itemLevel;
    echo "\n";
}

相关问题