sql中的join使用

join常用如下:

  left join : 左连接,返回左表中所有的记录以及右表中连接字段相等的记录。

  right join : 右连接,返回右表中所有的记录以及左表中连接字段相等的记录。

  inner join : 内连接,又叫等值连接,只返回两个表中连接字段相等的行。

  full join : 外连接,返回两个表中的行:left join + right join。

  cross join : 结果是笛卡尔积,就是第一个表的行数乘以第二个表的行数。

在使用jion 时,on 和 where 条件的区别如下:

on 条件是在生成临时表时使用的条件,它不管 on 中的条件是否为真,都会返回左(右)边表中的记录。

where 条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有 left(right) join 的含义(必须返回左(右)边表的记录)了,条件不为真的就全部过滤掉

总结:

在常用的left join、right join、full join  中:不管 on 上的条件是否为真都会返回 left 或 right 表中的记录;full 则具有 left 和 right 的特性的并集。

而 inner jion 没这个特殊性,则条件放在 on 中和 where 中,返回的结果集是相同的。

sql写法如下:

select t.indexs, t.fdjbh, t.dhh, t.vin, t1.c_data_no from table1 t left join table2 t1 on t1.c_vin = t.vin;

猜你喜欢

转载自www.cnblogs.com/zyanrong/p/12468316.html
今日推荐