cross join--交叉连接

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              |
+------------+--------------+--------------+----------------+

思路: 

  1. 利用 Cross join 将STUDETNS SUBJECTS 两张表组合起来
  2. 左连接 取得参加考试的次数

cross join 结果是笛卡尔积,就是第一个表的行数乘以第二个表的行数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值