我有两个表格如下所示:
Table Name : scores
+-------+-----------+--------------+-----------+
| UNID | name | score | PRID |
+-------+-----------+--------------+-----------+
| 1 | name_1 | 93 | 1 |
| 2 | name_2 | 71 | 1 |
| 3 | name_3 | 53 | 2 |
| 4 | name_4 | 82 | 2 |
| 5 | name_5 | 31 | 2 |
| 6 | name_6 | 68 | 3 |
+-------+-----------+--------------+-----------+
和
Table Name : user_dir
+-------+-----------+--------------+-----------+
| PRID | fname | city | gender |
+-------+-----------+--------------+-----------+
| 1 | fname1 | XX | m |
| 2 | fname2 | YY | f |
| 3 | fname3 | ZZ | f |
+-------+-----------+--------------+-----------+
对于来自 user_dir 的任何指定 PRID ,如何获取与得分的最高值对应的整行 PRID
例如,对于用户" fname2"如果PRID为2,我想按如下方式拉出整行(而不只是得分的值):
+-------+-----------+--------------+-----------+
| UNID | name | score | PRID |
+-------+-----------+--------------+-----------+
| 4 | name_4 | 82 | 2 |
我尝试使用" max"该行的功能,但它改为给出了使用该PRID找到的第一行,以及得分的正确(最大)值,如下所示:
+-------+-----------+--------------+-----------+
| UNID | name | score | PRID |
+-------+-----------+--------------+-----------+
| 3 | name_3 | 82 | 2 |
编辑:我误解了我的要求,最终结果需要有相应的"名称"最高分的价值,而不是最高分。
所以实际的最终结果是:
+-------+-----------+--------------+-----------+
| PRID | name | fname | score |
+-------+-----------+--------------+-----------+
| 1 | fname1 | name_1 | 93 |
| 2 | fname2 | name_4 | 82 |
| 3 | fname3 | name_6 | 68 |
答案 0 :(得分:1)
SELECT s.*
FROM scores s
WHERE PRID = 2 AND score = (SELECT MAX(score) FROM scores WHERE PRID = 2)
如果您想获取包含每个PRID
所有最高分的记录,那么您可以尝试以下操作:
SELECT s.*
FROM scores s
WHERE score = (SELECT MAX(score) FROM scores s1 WHERE s.PRID = s1.PRID)