获取相同ID的最高分数,然后与其他ID进行比较

时间:2012-10-10 03:38:18

标签: php mysql

表:

========================================
|id| document_id | sentence_id | score |
========================================
|1 |   3         |     1       | 0.324 |
|2 |   3         |     2       | 0.201 |
|3 |   5         |     1       | 0.181 |
|4 |   5         |     2       | 0.402 |
========================================

我希望每document_id获得最高分,然后将结果与其他document_id进行比较。我的目标是获得document_id. so from the example, the result must be 5 3

的序列
$q = mysql_query("SELECT document_id, MAX(score) as max_score FROM `tb_score` GROUP BY document_id ");
while ($row = mysql_fetch_array($q)) {
   $min = $row['max_score'];
}

我仍然得到错误的结果。求你帮帮我。

3 个答案:

答案 0 :(得分:1)

您似乎描述的SQL是:

SELECT document_id
        , MAX(score) as max_score
    FROM tb_score
    GROUP BY document_id
    ORDER BY MAX(score) DESC --or max_score, I'm not sure which MySQL will accept.

这有帮助吗?

除了:PHP中不推荐使用MySQL扩展名,您应该使用MySQL ImprovedPHP Data Objects来完成这项工作。

答案 1 :(得分:1)

SQL必须是这样的。

SELECT document_id, MAX(score) as max_score 
FROM `tb_score` GROUP BY document_id
ORDER BY max_score DESC

答案 2 :(得分:1)

You can't use alias in ORDER BY。因此,您必须在MAX(score)中使用ORDER BY。像这样:

SELECT document_id ,MAX(score) as Highscore
FROM tb_score
GROUP BY document_id
ORDER BY MAX(score) DESC;

或者使用子查询,您也可以这样做。

SELECT * FROM
(
SELECT document_id ,MAX(score) as Highscore
FROM tb_score
GROUP BY document_id
) A
ORDER BY Highscore DESC;

See this SQLFiddle