cross join 结果是笛卡尔积,就是第一个表的行数乘以第二个表的行数
1.Students table:
+------------+--------------+
| student_id | student_name |
+------------+--------------+
| 1 | Alice |
| 2 | Bob |
| 13 | John |
| 6 | Alex |
+------------+--------------+
2.Subjects table:
+--------------+
| subject_name |
+--------------+
| Math |
| Physics |
| Programming |
+--------------+
3.Examinations table
+------------+--------------+ | student_id | subject_name | +------------+--------------+ | 1 | Math | | 1 | Physics | | 1 | Programming | | 2 | Programming | | 1 | Physics | | 1 | Math | | 13 | Math | | 13 | Programming | | 13 | Physics | | 2 | Math | | 1 | Math | +------------+--------------+
以上表,如果获取参加考试的人次数(包含参加0次的)。
1.Students3条数据,2.Subjects4条数据
那么返回值应该是3*4=12条数据
如果简单的用left join 或者join是无法满足条件的。
sql文如下:
如
select
stu.STUDENT_ID
,stu.STUDENT_NAME
,sub.SUBJECT_NAME
,count(sub.subject_name) ATTENDED_EXAMS
from Students stu
cross join Subjects sub
left join Examinations exam
on stu.student_id = exam.student_id
and exam.subject_name = sub.subject_name
group by stu.student_id
,stu.student_name
,sub.subject_name
order by stu.student_id ,sub.subject_name
结果:
+------------+--------------+--------------+----------------+
| student_id | student_name | subject_name | attended_exams |
+------------+--------------+--------------+----------------+
| 1 | Alice | Math | 3 |
| 1 | Alice | Physics | 2 |
| 1 | Alice | Programming | 1 |
| 2 | Bob | Math | 1 |
| 2 | Bob | Physics | 0 |
| 2 | Bob | Programming | 1 |
| 6 | Alex | Math | 0 |
| 6 | Alex | Physics | 0 |
| 6 | Alex | Programming | 0 |
| 13 | John | Math | 1 |
| 13 | John | Physics | 1 |
| 13 | John | Programming | 1 |
+------------+--------------+--------------+----------------+
思路:
- 利用 Cross join 将STUDETNS SUBJECTS 两张表组合起来
- 左连接 取得参加考试的次数
cross join 结果是笛卡尔积,就是第一个表的行数乘以第二个表的行数