jion查询,是在不同表的字段之间的连接查询。
上一节的union子查询,在不同的行之间进行联合查询
内连接,外连接
内连接的结果只包含连接各方同时存在数据的记录。
外连接中只要有一方连接有数据就可以显示出来,没有数据的一方显示NULL
select t1.col, t2.col from t1 inner join t2 on t1.id = t2.t1_id; //意义:在连接时就进行判断,只取得符合条件的。
select t1.col, t2.col from t1 inner join t2 where t1.id = t2.t1_id; //先把所有可能的结果值取出来,然后在其中查找符合条件的
select t1.col, t2.col from t1 inner join t2 using (t1_id); //using 两个表的字段名必须有相同得字段(t1_id)
on和where虽然效果是一样的,但是连接的时候用on逻辑意义更清晰。
即先通过on去实现数据的连接,然后用where去过滤符合条件的。
内连接如果t1中存在,t2中找不到连接的对象,则不显示该条记录。
假设t1内容如下
col id
a 1
b 2
c 3
t2内容如下;
id t1_id col
1 1 A
2 2 B
3 3 C
内连接中如果不写on语句,则会全部遍历连接一遍,例如上面的例子检索结果为
a A
a A
a A
b B
b B
b B
c C
c C
c C
不加上on条件的连接,实际上等价于cross join
select t1.col, t2.col from t1 cross join t2;
select t1.col, t2.col from t1 inner join t2;
select t1.col, t2.col from t1 join t2;
外连接
所谓左右连接,体现的是在连接时谁是最重要的。重要的一方不允许为NULL。实际开发中一半用左连接,更符合思维习惯。
内连接是不允许任何一方没有数据的,所以没有左右之分,则外连接的时候left outer join中 outer可以省略,因为只要出现左,右,则肯定是外连接。
全连接的概念是两方任意一个不为NULL则显示,mysql中不支持。
select t1.col, t2.col from t1 left [outer] join t2 on t1.id = t2.t1_id;
左外连接,如果t1中有,在t2中找不到符合得内容,则t1显示,t2内容显示为NULL。
select t1.col, t2.col from t1 right [outer] join t2 on t1.id = t2.t1_id;
右外连接,如果t1中没有,在t2中有,则t1显示为NULL,t2内容显示。
内连接与外连接区别
外连接不能用where替代on,只能用on和using
外连接不可以省略条件,即必须添加on或者using
using和on的区别
using的话会会将所使用的列合并,而on则不会。比如
假设t1内容如下
col id
a 1
b 2
c 3
t2内容如下;
id col
1 A
2 B
3 C
select * from t1 join t2 on t1.id=t2.id;
查询的结果类似下面,不会将两个重复的id合并。
col id id col
a 1 1 A
select * from t1 join t2 on using (id);
查询的结果类似下面,将两个重复的id合并。
col id col
a 1 A
自然外连接,自然内连接
和名字相符,mysql自动使用有相同的字段进行连接。
select * from t1 nature join t2; //内连接
select * from t1 nature left [outer] t2;
select * from t1 nature right [outer] t2;
**小技巧**
1.当两个表中得字段不冲突的时候,字段前也可以不需要表前缀。但是为了规范,不冲突时最好也写上。
2.当表名字太长的时候可以用别名
select t1.col, t2.col from mylongtable1 as t1 left outer join mylongtable2 as t2 on t1.id = t2.t1_id;
同样虽然as可以去掉,但是不推荐。
3.2中得例子,在检索出数据时,两列都会显示col,这样又造成了混淆,进一步给字段起别名。
select t1.col as t1_col, t2.col as t2_col from mylongtable1 as t1 left outer join mylongtable2 as t2 on t1.id = t2.t1_id;
4.实际开发中用得最多的连接是左链接。
5.连接可以进行多级连接,如下三表连接
select * from t1 join t2 on t1.id=t2.id left jion t3 on t1=t3 where t3.name=“ok”;