连接两个表后如何显示5个最大值?

时间:2019-06-04 16:17:36

标签: mysql sql

我有2张桌子:

  • 用户(uid,rollno,名称)

users table

  • 结果(rid,uid,marks)

results table

所以我想显示最高的5分标记持有人,其卷号和标记类似-

MCA-03/17   16
MCA-01/17   15
MCA-04/17   8
MCA-02/18   6
MCA-06/17   5

我尝试过:

SELECT u.rollno, r.marks 
FROM users u 
JOIN results r ON r.uid = u.uid 
ORDER BY marks DESC 
LIMIT 5

但它没有显示前5个最高分。

2 个答案:

答案 0 :(得分:0)

您应该加入最多5个子查询

select  u.rollno, r.marks 
FROM users u 
INNER JOIN result r on r.uid = u.uid 
INNER JOIN  (
SELECT  r.marks 
ORDER BY marks DESC 
LIMIT 5
) t on t.marks = r.marks 

答案 1 :(得分:0)

您需要从结果中获得前5分并加入用户:

SELECT u.rollno, r.marks
FROM users u INNER JOIN (
  SELECT uid, marks 
  FROM results  
  ORDER BY marks DESC 
  LIMIT 5
) r ON r.uid = u.uid
ORDER BY marks DESC