Mysql将两个查询结果组合成一个基于公共分组的字段

时间:2016-05-07 09:04:19

标签: mysql

我需要结合

的结果
select max(mark), exam_seq, subject_seq from mark where section_seq = 1 
group by exam_seq, subject_seq;

select mark, exam_seq, subject_seq from mark where stu_seq = 1 
group by exam_seq, subject_seq;

到一个结果集。

两个查询都会返回相同数量的结果。第一个查询通过考试和科目获得给定班级组的最大分数;第二个查询通过考试和科目获得学生组的单独标记。

根据其他类似查询的回答,我试过

select max(mark), exam_seq, subject_seq from mark where section_seq = 1 
group by exam_seq, subject_seq 
union all
select mark, exam_seq, subject_seq from mark where stu_seq = 1 
group by exam_seq, subject_seq

但它会产生一个低于另一个的结果。

我需要的是一个结果 4列:mark,max(mark),exam_seq,subject_seq。

第二个查询的

'mark'和 来自第一次查询的'max(mark)'

请注意,两个sqls的where条件不同(基于两个不同的字段)。请建议。感谢。

以下是1个班级,2个考试,5个科目和2个学生的样本数据:

section_seq   exam_seq   subject_seq   stu_seq   mark
1             1          1             1         65
1             1          1             2         56
1             1          2             1         65
1             1          2             2         56
1             1          3             1         56
1             1          3             2         65
1             1          4             1         99
1             1          4             2         88
1             1          5             1         55
1             1          5             2         66
1             2          1             1         65
1             2          1             2         56
1             2          2             1         77
1             2          2             2         68
1             2          3             1         99
1             2          3             2          9
1             2          4             1         88
1             2          4             2         45
1             2          5             1         66
1             2          5             2         66

1 个答案:

答案 0 :(得分:0)

我假设你可以加入你的群组bys,这样你就可以用子查询来实现这一点GROUP_CONCAT

SELECT allMarks.mark, max(mark), exam_seq, subject_seq from mark 
LEFT JOIN(
    SELECT GROUP_CONCAT(mark) as mark
    FROM mark 
    WHERE stu_seq = 1 
    GROUP BY exam_seq, subject_seq
) allMarks
ON allMarks.exam_seq = mark.exam_seq 
AND allMarks.subject_seq= mark.subject_seq
WHERE mark.section_seq = 1 
GROUP BY mark.exam_seq, mark.subject_seq

如果我们有一些样本数据,我们可以就此提出建议并检查结构是否正确。