内连接
内连接:当进行内连接时,系统会自动忽略两个表中对应不起来的数据,结果包含两个表中有联系的所有数据;
自然连接
自然连接:自然连接只考虑两个关系中在共同属性上取值相同的元组对。结果中无null,不需要使用修饰词限制连接属性。
关键字:natural join
SELECT * FROM person NATURAL JOIN address;
内连接
关键字:inner join / join
必须使用 using 或 on指定连接属性/条件,否则产生的结果与交叉连接相同
SELECT * FROM students st INNER JOIN score sc using(id);
SELECT * FROM students st INNER JOIN score sc ON st.sid=sc.stu_id;
外连接
外连接:结果包含符合条件的数据,同时包含不符合条件的数据(分为左外连接、右外连接和全外连接)
左外连接
左外连接(left join):左表全部行+右表匹配的行,如果左表中某行在右表中没有匹配的行,则在相关联的结果集行中右表的所有选择列表列均为空值。
关键字:left join on / left outer join on
SELECT * FROM students st LEFT JOIN score sc ON st.sid=sc.stu_id;
使用场景:可以保持左表完整加入另一表中的数据。
右外连接
右外连接(right join):与左外连接恰恰相反,以右表为参照显示数据
right join on / right outer join on
SELECT * FROM students st RIGHT JOIN score sc ON st.sid=sc.stu_id;
使用场景:可以保持右表完整加入另一表中的数据。
全外连接
全外连接(full outer join,MySQL不支持):可通过Union
左外连接和右外连接来实现,不管匹配不匹配,全部显示出来,左表在右边没有的显示NULL,右表在左边没有的显示NULL。
SELECT * FROM students st LEFT JOIN score sc ON st.sid=sc.stu_id;
UNION
SELECT * FROM students st RIGHT JOIN score sc ON st.sid=sc.stu_id;
MySQL中存在交叉连接(cross join):返回左表中所有行与右表中所有行的组合,也称笛卡尔积。它有两种表述方式:
SELECT * FROM students CROSS JOIN score;
SELECT * FROM students,score;