从中选择最大值(选择查询)

时间:2019-04-04 11:33:45

标签: php mysql sql max

我有一个已经可以使用的SQL语句,但是我想添加另一个子选择查询,该查询为以下子选择查询返回(结果的最大值)

(select  count(*) from users where `score` =8 and `uni` = t.uni)*8 as 'rscore', 

这是我的代码

<?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++; 
 }
} 
?>

1 个答案:

答案 0 :(得分:3)

您可以使用conditional aggregationcountmax

select  uni, sum( case when score  =8  then 1 else 0 end )*8 as rscore,
        count(*) total,
        max(my_col) my_max 
from  users
group by uni

参考:
http://www.mysqltutorial.org/mysql-max-function/
http://www.mysqltutorial.org/mysql-count/