0

これは私のテーブルです

+------+-------+--------+
| NAME | MARKS | SCHOOL |
+------+-------+--------+
| N1   |    80 | S1     |
| N2   |    90 | S2     |
| N3   |    75 | S1     |
| N4   |    70 | S2     |
| N5   |    55 | S1     |
| N6   |    75 | S1     |
| N7   |    70 | S1     |
| N8   |    80 | S1     |
| N9   |    60 | S1     |
+------+-------+--------+

ここでは、各学校の生徒の名前、マークをマークの降順に表示しようとしています。また、最初の上位 3 点は、First、Second、Third として表示されます。

したがって、最終出力は次のようになります

+------+-------+--------+-------+
| NAME | MARKS | SCHOOL | PRIZE |
+------+-------+--------+-------+
| N1   |    80 | S1     | First |
| N8   |    80 | S1     | First |
| N3   |    75 | S1     | Second|
| N6   |    75 | S1     | Second|
| N7   |    70 | S1     | Third |
| N9   |    60 | S1     |       |
| N5   |    55 | S1     |       |
+------+-------+--------+-------+

次のコードを試しています.3つの異なるクエリを試しましたが、出力が得られません

<table width="100%" border="1">  
<tr>
<th>Name</th>
<th>Marks</th>
<th>Prize</th>
</tr>
<?php                     
$result = mysql_query("SELECT * FROM myTable WHERE SCHOOL= 'S1'
ORDER BY Marks Desc");

//$sql="SELECT * FROM myTable  AS t1  INNER JOIN (SELECT DISTINCT(Marks) 
AS best_marks FROM myTable WHERE SCHOOL= 'S1' ORDER BY Marks DESC LIMIT 3)
AS t2 ON t1.Marks = t2.best_marks ORDER BY Marks DESC, Name ASC";   


/* $sql = "SELECT * FROM myTable WHERE SCHOOL= 'S1' AND

 LEFT JOIN
 (select Marks from myTable order by Marks desc limit 1) AS max1
 ON myTable .Marks=max1.Marks
 LEFT JOIN
 (select Marks from myTable order by Marks desc limit 2,1) AS max2
 ON myTable .Marks=max2.Marks
 LEFT JOIN
 (select Marks from myTable order by Marks desc limit 3,1) AS max3
 ON myTable .Marks=max3.Marks;

 ORDER BY Marks Desc";
 */


while ($row = mysql_fetch_array($result)) 
{
?>
<tr>
<td><?php echo ucfirst($row['Name']);?></td>
<td><?php echo $row['Marks']; ?></td>

<td>

</td>
</tr> 
<?php   } ?>   
</table>
4

1 に答える 1

1

このクエリを試してください:

select t.NAME, t.MARKS, t.SCHOOL,
       if(prize=1,'First', if(prize=2,'Second', if(prize=3,'Third',null))) as Prize
  from
    myTable t,
    (select m.marks, @prize := @prize + 1 as prize
      from (select distinct marks 
              from myTable 
             where SCHOOL= 'S1' 
              order by marks desc
            ) m,
            (select @prize := 0) p
    ) as mp
  where t.marks = mp.marks
    and t.SCHOOL= 'S1'
order by t.marks desc

ここでは、フィドルで見ることができます:

新しいフィドル: http://sqlfiddle.com/#!2/d3635/28

于 2013-10-31T02:40:19.510 に答える