【问题标题】:How can I get maximum value from query? [duplicate]如何从查询中获得最大值? [复制]
【发布时间】: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++; 
    }
} 
?>

我想知道如何选择分数列的最大值并将其写入新列。我想要的结果是这样的:

【问题讨论】:

标签: php mysqli max


【解决方案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>
  ';

【讨论】:

  • 最大值来自(rscore)查询结果,而不是来自数据表中的分数列。 @Patrick B
猜你喜欢
  • 2020-03-29
  • 1970-01-01
  • 2019-09-01
  • 2020-01-03
  • 2022-10-05
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 2022-11-25
相关资源
最近更新 更多