数据库连接
自然连接
natural join
自然连接不用指定连接列,也不能使用ON语句,它默认比较两张表里相同的列,SELECT*FROM student NATURAL JOIN score;
内连接
inner join
和自然连接区别之处在于内连接可以自定义两张表的不同列字段。 内连接有两种形式:显式和隐式。
例:以下语句执行结果相同。
- 隐式的内连接,没有INNER JOIN,形成的中间表为两个表的笛卡尔积。
SELECT student.name,score.code FROM student,score WHERE score.code=student.code;
- 显示的内连接,一般称为内连接,有INNER JOIN,形成的中间表为两个表经过ON条件过滤后的笛卡尔积。
SELECT student.name,score.codeFROM student INNER JOIN score ON score.code=student.code;
外连接
outer join
- 左外连接
left outer join
:返回指定左表的全部行+右表对应的行,如果左表中数据在右表中没有与其相匹配的行,则在查询结果集中显示为空值。
例:SELECT student.name,score.codeFROM student LEFT JOIN score ON score.code=student.code;
- 右外连接
right outer join
:与左外连接类似,是左外连接的反向连接。SELECT student.name,score.codeFROM student RIGHT JOIN score ON score.code=student.code;
- 全外连接
full outer join
:把左右两表进行自然连接,左表在右表没有的显示NULL,右表在左表没有的显示NULL。(MYSQL不支持全外连接,适用于Oracle和DB2。)
在MySQL中,可通过求左外连接与右外连接的合集来实现全外连接。 例:SELECT student.name,score.codeFROM student LEFT JOIN score ON score.code=student.codeUNION SELECT student.name,score.code FROM student RIGHT JOIN score ON score.code=student.code;
- 交叉连接
cross join
:相当与笛卡尔积,左表和右表组合。SELECT student.name,score.code FROM student CROSS JOIN score ON score.code=student.code;