文章目录
- 1 Join 类型有哪些
- 2 Inner Join
- 3 Left Join
- 4 Right Join
- 5 Full Join
1 Join 类型有哪些
SQL Join 类型的区别
- Inner Join: 左,右表都有的数据
- Left Join: 左表返回所有的行, 右表没有的补充为 NULL
- Right Loin: 右表返回所有的行, 左表没有的补充为 NULL
- Full Outer Join: 左表 + 右表 所有数据
用户表:
答题表:
2 Inner Join
查询左表 和 右表都有的数据
用户表 user_no = 1000
和 答题表 user_no = 6543
, 不在交集范围, 没有在查询出来
-- inner join --
select tup.user_no, tup.university, tqpd.question_id, tqpd.result
from t_user_profile tup inner join t_question_practice_detail tqpd
on tup.user_no = tqpd.user_no;
3 Left Join
左表返回所有的行, 右表没有的补充为 NULL
用户表 user_no = 1000
对应的答题信息为空, 补充 NULL, 答题表 user_no = 6543
不在查询范围
-- left join --
select tup.user_no, tup.university, tqpd.question_id, tqpd.result
from t_user_profile tup left join t_question_practice_detail tqpd
on tup.user_no = tqpd.user_no;
4 Right Join
右表返回所有的行, 左表没有的补充为 NULL
答题表 user_no = 6543
对应的用户信息为空, 补充 NULL, 用户表 user_no = 1000
不在查询范围
-- right join --
select tup.user_no, tup.university, tqpd.question_id, tqpd.result
from t_user_profile tup right join t_question_practice_detail tqpd
on tup.user_no = tqpd.user_no;
5 Full Join
在 MySQL 中没有 Full Join, 可以用 left join 和 right join 实现
用户表 user_no = 1000
对应的答题信息补充 NULL, 答题表 user_no = 6543
对应的用户信息补充 NULL
-- left join and right join --
select tup.user_no, tup.university, tqpd.question_id, tqpd.result
from t_user_profile tup left join t_question_practice_detail tqpd
on tup.user_no = tqpd.user_no
union
select tup.user_no, tup.university, tqpd.question_id, tqpd.result
from t_user_profile tup right join t_question_practice_detail tqpd
on tup.user_no = tqpd.user_no;