数据库的多种连接查询操作说明
在数据库中涉及到多表查询的时候,有多种连接查询操作,分别如下所示:
- inner join on
- left join on
- left join on where
- *right join on
- right join on where
- outlier join on
- from table1, table2 where table1.condition1=table2.condition2
Inner join on
使用jnner join on操作的句法如下所示
select <fields> from table1 as t1 inner join table2 as t2 on
t1.condition=t2.condition
使用这种连接操作是为了返回两个表或者多个表之间的交集。在查询到结果集中,会以记录最多的表的记录行数为主,其他表的内容可能重复出现。
left join on
使用 left join on操作的句法如下所示
select <fields> from table1 as t1 left join table2 as t2 on
t1.condition=t2.condition and t1.condition2=t2.condition2 ...
使用这种连接操作是要以表1的记录为主,依据on后面跟着的限制条件,从表2中的查询符合限制条件的结果。最终拼接成一个完整的结果集。
left join on where
使用 left join on where 操作的句法如下所示
select <fields> from table1 as t1 left join table2 as t2 on
t1.condition=t2.condition and t1.condition2=t2.condition2 ...
where t1.condtion=? (and so on.)
使用这种连接操作是在left join on的基础上添加了where操作,使用where操作为查询的结果集添加过滤条件。
right join on
使用 right join on操作的句法如下所示
select <fields> from table1 as t1 right join table2 as t2 on
t1.condition=t2.condition and t1.condition2=t2.condition2 ...
使用这种连接操作是要以表2的记录为主,依据on后面跟着的限制条件,从表2中的查询符合限制条件的结果。最终拼接成一个完整的结果集。
right join on where
使用 right join on操作的句法如下所示
select <fields> from table1 as t1 right join table2 as t2 on
t1.condition=t2.condition and t1.condition2=t2.condition2 ...
使用这种连接操作是在right join on的基础上添加了where操作,使用where操作为查询的结果集添加过滤条件。
outer join on
使用outer join on操作的句法如下所示
select <fields> from table1 as t1 outer join table2 as t2 on
t1.condition=t2.condition
使用这种连接操作是为了返回两个表或者多个表之间的并集。在查询到结果集中,某个表中的某些记录行可能重复出现多次,对于某个表中没有满足on后面的限制条件的数据记录,用null表示。
from table1, table2 where table1.condition1=table2.condition2
使用操作的句法如下所示
select <fields> from table1 as t1, table2 as t2 where
t1.condition=t2.condition
这种方法也成为隐式内连接操作,查询结果只有满足限制条件的结果集。针对这个方法和内连接查询的区别,网上说法不一。但是,这两种语句在优化后的sql是一样的,可能目前各个数据库的优化技术的层次不齐,导致了查询速度的差异性。