用CROSS JOIN联接三个表

时间:2018-06-21 15:55:15

标签: mysql join left-join inner-join right-join

我有三个表:

student:        sub:           marks:

id | name     id | sub         stud_id | sub_id | marks
---+--------  ---+------------  --------+----------+------
 1 | Peter     1 | English            1 |        1 |    80
 2 | Alice     2 | Maths              1 |        2 |    70
               3 | History            2 |        1 |    90
                                      2 |        2 |    80

我需要进行查询以返回以下内容:

 name  | subjects  | marks
-------+-----------+----------------------------
  Peter | English  | 80
  Peter | Maths    | 70
  Peter | History  | 0

这是我尝试过的:

select * 
from student s 
LEFT JOIN stud_marks m ON s.id = m.stud_id 
RIGHT JOIN subjects sub ON sub.id = m.sub_id

这让我

name  | marks  | sub
------+--------+----------
Peter | 80     | English  
Peter | 70     | Maths    
Alice | 90     | English  
Alice | 80     | Maths    
      |        | History

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您将把Peter和所有潜艇交叉加入。然后外部加入标记:

select
  peter.name,
  sub.sub,
  coalesce(marks.marks, 0) as marks
from (select * from student where id = 1) peter
cross join sub
left join marks on marks.stud_id = peter.id and marks.sub_id = sub.id
order by sub.sub;

(实际上没有必要在子查询中选择Peter,但我认为这很清楚我们在这里做什么。我们也可以将带有标记的学生交叉连接,并将其限制为WHERE子句中的Peter。)