mysql的自联结、天然联结、内部联结、等值联结、不等值联结、外部联结、交叉联结等替你整理好了,爱看不看。

自联结

就是一个表本身和本身联结,通常用来替代子查询数据库

好比班上有1个学生数学考了100分,你不知道他是谁,你想知道他的其余学科的成绩spa

新手的写法code

select student_id from score where type='mathematics' and score=100(假设结果为27)
select * from score where student_id=27
或者
select * from score where student_id=(
    select student_id from score where type='mathematics' and score=100
)

自联结的写法blog

select t1.* from score as t1,score as t2 where t1.student_id=t2.student_id and t2.type='mathematics' and t2.score=100
select t1.* from score as t1 inner join score as t2 on t1.student_id=t2.student_id where t2.type='mathematics' and t2.score=100

天然联结

不管什么时候对表进行联结,应该至少有一个列出如今不止一个表中(被联结的列)图片

标准的联结返回全部数据,甚至相同的列屡次出现数学

天然联结排除屡次出现,使每一个列只返回一次it

数据库经过本身的判断并使用表内全部相同的字段做为联结条件完成联结过程,不须要指定联结条件io

通常的写法是第1个表用*指定字段,其余的表用明确的表字段指定class

最好不要让数据库自动完成联结,不推荐使用select

select * from t1 natural join t2(效果有点相似inner join)
select * from t1 natural left join t2(效果有点相似left join)
select * from t1 natural right join t2(效果有点相似right join)

内部联结(又叫等值联结)

联结的2个表必须联结条件匹配才会获得数据

内部联结通常都是天然联结,极可能咱们永远都不会用到不是天然联结的内部联结

select a.f1,b.f2 from a,b where a.f3=b.f4(不推荐这样的写法)
select a.f1,b.f2 from a inner join b on a.f3=b.f4(inner关键字能够省略)

若是两个表是根据字段名同样的字段联结的,能够这样写

select t1.id,t2.name from t1 inner join t2 using(f)

外部联结

外部联结根据状况来肯定是否包含那些在相关表中没有匹配的行

1.左外部联结(又叫左联结)

左表的行必定会列出,右表若是没有匹配的行,那么列值就为null

特别须要注意的是若是右表有多行和左表匹配,那么左表相同的行会出现屡次

select a.f1,b.f2 from a left outer join b on a.f3=b.f4(outer关键字能够省略)

2.右外部联结(又叫右联结)

和左联结相似,只不过以右表为主表而已,左联结和右联结能够相互转化

select a.f1,b.f2 from a right outer join b on a.f3=b.f4(outer关键字能够省略)

3.全外部联结

返回左表和右表的全部行,无论有没有匹配,同时具备左联结和右联结的特性

select a.f1,b.f2 from a full outer join b on a.f3=b.f4(outer关键字能够省略)

交叉联结

生成笛卡尔积,它不使用任何匹配或者选取条件,而是直接将一个数据源中的每一个行与另外一个数据源的每一个行都一一匹配

select * from a cross join b

UNION和UNION ALL

UNION不容许同一行(每一个字段都同样)重复出现,而UNION ALL则没有这个限制

select A,B from u1
union all
select A,B from u2

关于联结的示意图

图片描述

相关文章
相关标签/搜索