【发布时间】:2019-04-05 18:31:00
【问题描述】:
我正在使用 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++;
}
}
?>
我想知道如何选择分数列的最大值并将其写入新列。我想要的结果是这样的:
【问题讨论】:
-
请分享您的表格数据
-
代码显示根本没有尝试这样做。 VTC 太宽泛了。将记录放入数组并获取最大值php.net/max 或要求数据库执行此操作很简单dev.mysql.com/doc/refman/8.0/en/example-maximum-column.html
-
i.stack.imgur.com/tm5m7.png @Rakesh Jakhar
-
另外,您不需要那些子查询。将第一个替换为
SUM(score=8)*8,第二个替换为COUNT(*)