выберите максимальное значение из (выберите запрос) - PullRequest
0 голосов
/ 04 апреля 2019

У меня есть оператор 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 Ответ

3 голосов
/ 04 апреля 2019

Вы можете использовать conditional aggregation, count и max

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/

...