简体   繁体   中英

Get corresponding row properties for min value in column from database table

I have a MySQL table with the following data:

ID, PERSON_NAME, SCORE, DATE

I'm trying to write a query where I can get the minimum SCORE value and the corresponding PERSON_NAME value. I've tried the following query:

min_query = "SELECT PERSON_NAME, MIN(SCORE) FROM HTMLSCORES"

cursor.execute(min_query)

result = cursor.fetchone()
name = result[0]
min_score = result[1]

However, the name value is always the same and seems to be the first entry in the table. I would like to get the corresponding PERSON_NAME value for the MIN(SCORE). How do I go about writing that query?

Try this:

SELECT PERSON_NAME, SCORE
FROM HTMLSCORES
WHERE SCORE =
(SELECT MIN(SCORE)
 FROM HTMLSCORES)

Look at the sub-query first. We can find the MIN score from your table using the MIN function. Then, in the main query, we select the row or rows where score in that row matches the sub-query score.

Your first attempt doesn't work because the query is looking at the person name and the score independently. Writing the query this way will link them together.

min_query = "SELECT PERSON_NAME, MIN(SCORE) AS 'Min_Score' FROM HTMLSCORES GROUP BY PERSON_NAME ORDER BY PERSON_NAME"

This will return a list of all PERSON_NAME and their min score.

If you are after a particular user and know what the PERSON_NAME should be use

pyPerson = 'Name Here'    
min_query = "SELECT PERSON_NAME, MIN(SCORE) AS 'Min_Score' FROM HTMLSCORES  WHERE PERSON_NAME = '" + str(pyPerson) + "' GROUP BY PERSON_NAME" 

Forgive my crude python but it should work SQL wise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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