如何在mysql表中找到最高值

时间:2011-03-30 05:02:38

标签: php mysql

我有一个mysql表,即

st_id | name | email | maths | chemistry | bio | social_study
1     | john |@a.com | 20    |  23       | 10  |  15


我的问题是如何才能找到最高的主题分数,第二个最后的分数等等         请注意,所有主题字段都具有int(11)值

4 个答案:

答案 0 :(得分:5)

将数据库分成3个表格,如:

学生:

st_id | name | email  
1     | john |@a.com  

课程:

cr_id | name  
1     | maths  
2     | chemistry  
3     | bio  
4     | social_studies

学生课程:

st_id | cr_id | score  
1     | 1     | 20   
1     | 2     | 23   
1     | 3     | 10   
1     | 4     | 15  

现在你可以做到:

SELECT s.name, MAX(sc.score) FROM Students s INNER JOIN StudentCourses sc ON s.st_id = sc.st_id;

答案 1 :(得分:1)

SELECT * FROM <table>
ORDER BY <field> DESC
LIMIT <needed number of rows>

示例:

SELECT * FROM <table>
ORDER BY maths+chemistry+bio+social_study DESC
LIMIT 3

答案 2 :(得分:0)

严格的PHP方法:我假设您想要保持与字段名称的关联。在这种情况下,只需在查询结果中的每一行使用asort($row);,假设您将该行作为数组提取。 asort将数组从最低值到最高值(如果需要,使用其他标志来调整结果),同时保持键。然后,foreach循环将允许您按排序顺序处理每个键/值对。

答案 3 :(得分:0)

st_id | name | email | maths | chemistry | bio | social_study

1     | john |@a.com | 20    |  23       | 10  |  15

查询可以用于最高分

SELECT id,GREATEST(mark,mark1,mark2) AS `top`  FROM `students`