我正在使用PHP和MySQL,并且正在寻找一个选择查询以从查询结果中获取最大值和值。我有此表供用户使用(ID,大学,分数)。 我尝试过:
<?php
$connect = mysqli_connect('localhost', 'root', '', 'test') or die ( mysqli_error($connect));
$output = '';
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "select t.uni,
(select count(*) from users where `score` =8 and `uni` = t.uni)*8 as 'rscore',
(select count(*) from users where `uni` = t.uni) as 'total'
from users t group by t.uni
";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
$output .= '
';
$i = 1;
while ($row = mysqli_fetch_array($result)) {
echo '
<tr>
<td align="center">' . $i . '</td>
<td width="10%">' . $row["uni"] . '</td>
<td align="center">' . $row["rscore"] . '</td>
<td align="center">' . $row["total"] . '</td>
</tr>
';
$i++;
}
}
?>
我想知道如何为得分列选择最大值并将其写入新列。我想要这样的结果:
答案 0 :(得分:-1)
您的查询可以是:
select t.uni,
(select count(*) from users where `score` = 8 and `uni` = t.uni) * 8 as 'rscore',
(select count(*) from users where `uni` = t.uni) as 'total'
(select max(score) from users) as 'Max_Score'
from users t
group by t.uni
在回显表行的位置,只需添加Max_Score列:
echo '
<tr>
<td align="center">' . $i . '</td>
<td width="10%">'.$row["uni"].'</td>
<td align="center">'.$row["rscore"].'</td>
<td align="center">'.$row["total"].'</td>
<td align="center">'.$row["Max_Score"].'</td>
</tr>
';