根据外键获取最小值

时间:2015-04-26 19:32:51

标签: mysql sql

我被困在如何从学生表中获得marks表和student信息的学生最低分数。

编辑:抱歉没有提及,但我需要用户1的结果,st1

学生

id name
1  st1
2  st2

标记

student_id course_name marks
1          C++         55
1          OOP         65
1          AI          45  //need this lowest result for st1
2          C++         82
2          STATS       74
2          OS          20 // lowest marks are these for st2 or overall

编辑忘记输入名称st1:

期望的输出:

id name course_name MinMarks
1  st1  AI          45

我尝试了这个查询,但它提供了错误的course_name(C ++)第一行的课程名称

SELECT s.id, s.name, m.course_name, MIN(m.marks) FROM student s
JOIN marks m
ON s.id = m.student_id
Where s.id = 1

输出:

id name course_name MinMarks
1  st1  C++         45

5 个答案:

答案 0 :(得分:4)

您可以使用子查询:

select *
from marks 
where marks = (select min(marks) from marks)

left join

select m.*
from marks m
left join (select min(marks) as marks from marks) m_min on m.marks = m_min.marks
where m_min.marks is not null

它保证如果有一个学生的最小mark,则会显示所有这些学生。

left join可以提高性能,您可以检查执行计划以确定。

PS:如果您还需要从name表中检索student(未在所需输出中说明),您可以执行在查询中执行的join操作:

使用子查询:

select m.student_id
     , s.name
     , m.course_name
     , m.marks 
from student s
join marks m on s.id = m.student_id
where m.marks = (select min(marks) from marks)

使用left join

select m.student_id
     , s.name
     , m.course_name
     , m.marks 
from student s
join marks m on s.id = m.student_id
left join (select min(marks) as marks from marks) m_min on m.marks = m_min.marks
where m_min.marks is not null

修改

事实证明, OP marksstudent idid = 1)需要至少select m.student_id , s.name , m.course_name , m.marks from student s join marks m on s.id = m.student_id left join (select student_id, min(marks) as marks from marks group by student_id) p on s.id = p.student_id and p.marks = m.marks where s.id = 1 and p.student_id is not null ,所以:< / p>

yield

答案 1 :(得分:0)

试试这个:

Select s.id, s.name, m.course_name, m.marks From student s 
right join marks m 
on s.id = m.user_id where m.marks = MIN(m.marks);

答案 2 :(得分:0)

尝试类似

的内容
select
  s.id,
  s.name,
  m.course_name,
  m.marks
from
  student s 

  inner join marks m on
    m.student_id = is.id

  inner join (
    select
      student_id,
      min(marks) min_mark
    from
      marks m
    group by
      student_id
  ) min_marks on
    min_marks.student_id = s.id and
    min_marks.student_id = m.student_id and
    min_marks.min_mark = m.marks

答案 3 :(得分:0)

如果您只找到一个学生的最低分数,我建议order bylimit

SELECT s.id, s.name, m.course_name, m.marks
FROM student s JOIN
     marks m
     ON s.id = m.user_id
ORDER BY m.marks ASC
LIMIT 1;

如果您正在寻找具有相同最低分数的所有学生,此解决方案将无效。

答案 4 :(得分:0)

SELECT s.id, s.name, m.course_name, m.marks
FROM marks m
JOIN student s
ON m.student_id = s.id
WHERE m.student_id=1 AND m.marks = (SELECT MIN(marks) FROM marks WHERE student_id=1)