aJoin在三张桌子上有类似的声明

时间:2017-10-31 02:00:30

标签: mysql sql

我有三个学生表,科目和分数。 学生

Student
id,name,address
1,tom,London
2,sam,USA
3,cal,Fort

subject
id,subjectname
1,maths
2,Science

marks
studid,subid,marks
1,1,30
1,2,40
2,1,60
2,2,70

需要对学生和科目进行搜索查询 所以我在学生LIKE CONCAT('%', "cal", '%')

上使用了类似的查询
    SELECT student.name,
        subject.name,
       marks.marks
  FROM marks
  RIGHT JOIN student ON student.name LIKE CONCAT('%', "cal", '%') AND student.id = marks.stuid 
 RIGHT JOIN subject ON subject.id = marks.subjectid

在搜索学生时需要这样的输出

Studentname subject Marks
cal,maths,0
cal,science,0

Studentname subject Marks
tom,maths,30
tom,science,40

Studentname subject Marks
sam,maths,60
sam,science,70

我同时需要所有科目和所有学生如果没有通过任何值,则应该看到

Studentname subject Marks
tom,maths,30
tom,science,40    
sam,maths,60
sam,science,70
cal,maths,0
cal,science,0

2 个答案:

答案 0 :(得分:1)

你需要所有科目。所以,从那开始并使用left join

SELECT s.name, su.name, coalesce(m.marks, 0)
FROM subjects su LEFT JOIN
     marks m
     ON m.subjectid = su.id LEFT JOIN
     student s
     ON s.name LIKE CONCAT('%', 'cal', '%') AND
        s.id = m.stuid ;

如果您需要所有学生和科目,请从cross join开始:

SELECT s.name, su.name, coalesce(m.marks, 0)
FROM subjects su CROSS JOIN
     students s LEFT JOIN
     marks m
     ON m.subjectid = su.id AND s.id = m.stuid ;

答案 1 :(得分:1)

这可能是你想要的

SELECT student.name,
        subject.name,
        IFNULL(marks.marks,0) 

FROM (student JOIN subject) left join marks on student.id = marks.studid and subject.id = marks.subid
where student.name LIKE CONCAT('%', "cal", '%')