仅在相同的ID中显示一行

时间:2014-11-13 09:38:47

标签: php mysql sql

我想问一下如何只在同一个id中显示一行,在下面的示例中,我只想在表中显示最高分数结果。

这是我的代码

    $query = "SELECT * FROM memberdata ORDER BY score DESC";
    echo "<table border=1>
    <tr>
    <th> id </th>
    <th> score </th>

    </tr>";

    while($row = mysqli_fetch_array($result)) {

        echo "<tr>";
        echo "<td>" . $row['id'] . "</td>";
        echo "<td>" . $row['score'] . "</td>";
        echo "</tr>";
    }

    echo "</table>";

输出

id score 
1  5000
1  4000
1  3000
1  500
2  3000
2  1000

3 个答案:

答案 0 :(得分:4)

使用分组

SELECT id, MAX(score) AS score FROM memberdata GROUP BY id

答案 1 :(得分:3)

试试这个:

SELECT id, MAX(score) AS score FROM memberdata GROUP BY id

或者这个:

SELECT * FROM memberdata ORDER BY score DESC LIMIT 1

答案 2 :(得分:0)

您需要先迭代才能找到maxrow。

    $query = "SELECT * FROM memberdata ORDER BY score DESC";
    echo "<table border=1>
    <tr>
    <th> id </th>
    <th> score </th>

    </tr>";

    $maxrow = mysqli_fetch_array($result);
    while($row = mysqli_fetch_array($result)) {
        if ($maxrow['score'] > row['score']) maxrow = row;
    }
    echo "<tr>";
    echo "<td>" . $maxrow['id'] . "</td>";
    echo "<td>" . $maxrow['score'] . "</td>";
    echo "</tr>";
    echo "</table>";