2011-08-26 193 views
0

我有这样的MySQL的三个表,复杂查询

triz_sti 

stu_id name 
----------------- 
1   x1 
2   x2 


triz_sub 

sub_id sub_name 
------------------ 
1   english 
2   maths 
3   science 


triz 

stu_id sub_id marks 
------------------------- 
1   1  23 
1   2  56 
1   3  83 
2   1  78 
2   2  23 
2   3  50 

我要像 显示所有学科,在与学生姓名perticular主题higest标记的结果,

max_marks sub_name  student_name 
-------------------------------------- 
78   english  x2 
56   maths  x1 
83   science  x2 

所以请帮助这个输出,我想,我已经尝试过,但我没有得到它的愿望输出。

+0

是的,这看起来像一个家庭作业可疑。向我们显示您的查询。我会给你一个提示:MAX()和JOIN。 –

+0

@Riho作业标签不被弃用? (http://meta.stackexchange.com/questions/60422/is-homework-an-exception/70233) – glglgl

回答

1

这样的事情呢?

SELECT 
    t.stu_id, t.sub_id, t.marks 
FROM 
triz t 
JOIN (SELECT sub_id, MAX(marks) max_mark FROM triz GROUP BY sub_id) a ON (a.sub_id = t.sub_id AND a.max_mark = t.marks) 

当然,您需要将其与名称查找表结合使用。

不得不说,它在这里很早,所以我可能错过了一些东西。

BR

0

在这种情况下,一般情况下,简化语法是

SELECT stuff FROM joined tables ORDER BY whatever 

最简单的是ORDER BY:你想排序标记下降,所以你ORDER BY marks DESC

数据从哪里来?从triz,加入到其他人。所以

triz JOIN triz_sti USING (stu_id) JOIN triz_sub USING (sub_id) 

而你想显示的标志。

所以,你得到

SELECT marks, sub_name, name AS student_name 
    FROM triz JOIN triz_sti USING (stu_id) JOIN triz_sub USING (sub_id) 
    ORDER BY marks DESC 

其余的我留给你。 :-)