将一张桌子连接到其他桌子

时间:2019-03-31 14:28:15

标签: mysql

i have 3 tables as the following:

学生

---------------
id     name
---------------
1      Joe
2      mark
3      mike
---------------

主题

-----------------------------------
id    student_id    name
-----------------------------------
1         1          math
2         1          english
3         1          french
4         1          history
5         2          math
6         2          english
7         2          french
8         3          math
9         3          english
-----------------------------------

考试

-----------------------------------
ID  Student_id   mark
-----------------------------------
1    1           10
2    1           10
3    1           10
4    1           10
5    2           5
6    2           5
7    2           5
8    3           2
9    3           2
-----------------------------------
SELECT
    student.id, student.name AS 'NAME',
    COUNT(subject.id) AS 'SUBJECTS',
    SUM(exam.mark) AS 'MARKS'
FROM
    'student'
INNER JOIN subject
ON   subject.student_id = student.id

LEFT JOIN exam
ON exam.student_id = student.id
GROUP BY
    student.id
  

我想在学生和主题,学生和考试之间加入   我加入第三张桌子时出现问题了
  复制结果。

     

我成功地加入了前两个表,但是当我加入>第三个表时,它复制了计数。

我需要的结果是:

----------------------------------- 
ID       NAME     SUBJECTS     MARKS 
----------------------------------- 
1         joe        4          40
2         mark       3          15
3         mike       2           4

2 个答案:

答案 0 :(得分:2)

这里一种简单的方法是对subjectexam表分别进行聚合,然后将它们联接:

SELECT
    s.id,
    s.name AS NAME,
    COALESCE(su.cnt, 0) AS SUBJECTs,
    COALESCE(e.marks, 0) AS MARKS
FROM student s
LEFT JOIN
(
    SELECT student_id, COUNT(*) AS cnt
    FROM subject
    GROUP BY student_id
) su
    ON s.id = su.student_id
LEFT JOIN
(
    SELECT student_id, SUM(mark) AS marks
    FROM exam
    GROUP BY student_id
) e
    ON s.id = e.student_id;

enter image description here

Demo

请注意,我在上面使用了左联接,因为给定的学生可能在subjectexam表中根本没有任何条目。在这种情况下,我们默认将他的计数/总和分配为零。<​​/ p>

答案 1 :(得分:1)

您可以通过直接查询每个学生ID来获取汇总列:

select 
  s.id, s.name,
  (select count(*) from subject where student_id = s.id) subjects,
  (select sum(mark) from exam where student_id = s.id) marks
from student s

请参见environment variables