我需要在某列中获得具有最低值的3行,然后反转这3行的顺序。因此,如果具有最低值的3行是A,B和C,我需要将它们排序为C,B和A.我可以在单个SQL语句中执行此操作吗?
$sql = "SELECT * FROM ratings_table ORDER BY rating DESC LIMIT 3";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
echo "<td>".$row['rating']."</td>";
}
}
使用此代码,我将得到正确的结果,但顺序错误。
答案 0 :(得分:7)
您需要使用子查询,如下所示:
SELECT *
FROM
(
SELECT *
FROM ratings_table
ORDER BY rating ASC LIMIT 3
) a
ORDER BY rating DESC
这将取最低的三个结果,然后翻转顺序。
答案 1 :(得分:0)
只有子查询才有效。首先,选择3个最低值,然后对它们进行排序。
类似的东西:
SELECT * FROM (
SELECT <COLUMN_VALUE>
FROM <YOUR_TABLE>
ORDER BY <COLUMN_VALUE> LIMIT 3
) T
ORDER BY <COLUMN_VALUE> DESC
答案 2 :(得分:0)
$sql = "SELECT * FROM ratings_table ORDER BY rating DESC LIMIT 3";
$result = mysqli_query($conn, $sql)->fetch_all();
krsort($result)
foreach ($result as $row)
{
echo "<td>".$row['rating']."</td>";
}