在group by子句MySQL中获取额外的属性

时间:2018-12-07 04:54:56

标签: mysql innodb

我有以下SQL关系模式

create table students(
  s_id int primary key auto_increment,
  s_name char(30),
  s_city char(30),
  s_number char(10)
)

create table subjects(
  sub_id int primary key auto_increment,
  sub_name char(30)
);

create table marks(
  m_id int primary key auto_increment,
  s_id int,
  sub_id int,
  marks int CHECK (marks <= 100 AND marks >= 0)
);

数据库存储学生的信息以及每个学科中的分数。

我可以使用以下SQL查询来获取每个主题中获得的最高分。

select sub_name, max(marks) as highest from subjects as sub, marks as m where sub.sub_id = m.sub_id group by sub_name;

它给了我以下结果:

+-----------+---------+
| sub_name  | highest |
+-----------+---------+
| Chemistry |     100 |
| Maths     |      98 |
| Physics   |      90 |
+-----------+---------+

现在,我想为上述结果添加一个额外的属性,即s_name,它将指定获得这些成绩的学生的姓名,为此我使用了以下查询。

select sub_name as subject, s_name as student, min(marks) as lowest from subjects as sub, marks as m, students as s where s.s_id = m.s_id and sub.sub_id = m.sub_id group by sub_name;

它给了我以下结果。

+-----------+-------------+--------+
| subject   | student     | lowest |
+-----------+-------------+--------+
| Chemistry | Mohd Shibli |     86 |
| Maths     | Mohd Shibli |     96 |
| Physics   | Mohd Shibli |     79 |
+-----------+-------------+--------+

获得的结果不正确,因为在“学生”列中,它获取的是第一个仅供学生使用的名称,而不是获取正确的名称。

任何人都可以帮我编写查询,该查询可以给出每个学科获得的最高分以及哪个学生获得的最高分的结果。

1 个答案:

答案 0 :(得分:0)

您可以在下面使用相关子查询尝试

select sub_name as subject, s_name as student,m.marks
from marks m 
inner join subjects as sub on m.sub_id=sub.sub_id
inner join students as s m.s_id=s.s_id
WHERE m.marks =
   (SELECT MAX(mm.marks) FROM marks mm GROUP BY 
         mm.sub_id HAVING mm.sub_id=m.sub_id)