All rights reserved.No part of this article may be reproduced or distributed by any means,or stored in a database or retrieval system,without the prior written permission of persistenceGoing author
https://blog.csdn.net/persistencegoing/article/details/84376427
One student scores table student, the data structure is such
id (the current table ID) student_id (student ID) line (score) subject_type (account type)
1 1 80 1
2 1 78 1
3 1 56 1
4 2 99 1
5 2 20 1
I think the student group, the highest score in each of a data packet that:
Several first-come, wrong wording:
(1)SELECT
max.*, MAX(max.line) lineMax
FROM
(SELECT * FROM student) max
GROUP BY
student_id
The wording you will find the data line and columns may be inconsistent lineMax
(2)SELECT
max.*, MAX(max.line) lineMax
FROM
(
SELECT
*
FROM
student
ORDER BY
line DESC
) max
GROUP BY
student_id
You might say that the sort after regrouping on the right, I'm sorry, may still be a problem for some smaller partners in this case
(3)SELECT
max.*, MAX(max.line) lineMax
FROM
(
SELECT
*
FROM
student
ORDER BY
line DESC
) max
GROUP BY
student_id
HAVING lineMax=line
In this case, the data is on the surface, but after a large amount of data you will find that some data loss, but it is still wrong
Correct wording:
SELECT
max.*, MAX(max.line) lineMax
FROM
(
SELECT
*
FROM
student
ORDER BY
line DESC
LIMIT 100
) max
GROUP BY
student_id
After mysql5.7 after release, you must be reordered plus limit keywords, 200,000 test data is correct, pro-test verification
Note:
limit must be added, if not, then data will not be sorted first by explain view the execution plan, you can see there is no limit of time, one less DERIVED operation.
The following SQL data is available to verify each
SELECT
*
FROM
student
WHERE
student_id = 69
ORDER BY
line DESC
LIMIT 100
I hope we are concerned about a wave, to prevent future lost, in need can learn from each other java plus group discussion, learning routes to explore, experience sharing and job java
Group number: 721 515 304