简体   繁体   English

如何在mysql表中找到最大值

[英]how to find the highest value in mysql table

i have a mysql table ie 我有一个MySQL表即

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


my question is how can i find the highest subject score, the second last and so on 我的问题是我如何才能找到最高的学科分数,倒数第二等等
Note that all the subject fields have int(11) values 请注意,所有主题字段均具有int(11)值

Break your database into 3 tables like: 将数据库分为3个表,例如:

Students: 学生们:

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

Courses: 课程:

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

StudentCourses: 学生课程:

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

Now you can do: 现在您可以执行以下操作:

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

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

Example: 例:

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

Strictly PHP method: I assume you want to maintain association with field names. 严格的PHP方法:我假设您想与字段名称保持关联。 In that case, just use asort($row); 在这种情况下,只需使用asort($row); on each row in your query result, assuming you fetched the row as an array. 在查询结果的每一行上,假设您以行的形式获取该行。 asort will sort the array from lowest value to highest (with additional flags to tweak the results if needed), while maintaining keys. asort将从最低值到最高值对数组进行排序(如果需要,可以使用其他标志来调整结果),同时保持键值不变。 A foreach loop will then allow you to work with each key/value pair in the sorted order. 然后,一个foreach循环将使您可以按排序顺序使用每个键/值对。

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

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

The query can be for top marks 查询可以是最高分

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM