[英]Get corresponding row properties for min value in column from database table
I have a MySQL table with the following data: 我有一个包含以下数据的MySQL表:
ID, PERSON_NAME, SCORE, DATE 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. 我正在尝试编写一个查询,以获取最小的SCORE值和相应的PERSON_NAME值。 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).
我想获取MIN(SCORE)的相应PERSON_NAME值。 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.
我们可以使用MIN函数从您的表格中找到MIN分数。 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. 这将返回所有PERSON_NAME及其最低分数的列表。
If you are after a particular user and know what the PERSON_NAME should be use 如果您是某个特定用户,并且知道应该使用什么PERSON_NAME
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. 原谅我的原始python,但它应该可以在SQL上正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.