有2个表
table1
user_id user_name user_pss
1 aaa a
2 bbb b
3 ccc c
table2
user_id user_power
1 111000
2 000111
使用sql语句查询
正常状态(内联接):
select table1.user_id, table1.user_name, table2.user_power
from table1,table2 where table1.user_id = table2.user_id (简单方式)
或者 select table1.user_id, table1.user_name, table2.user_power
from table1 ( inner) join table2 on table1.user_id = table2.user_id
但是这样检索出来的数据只有2条:
user_id user_name user_power
1 aaa 000111
2 bbb 111000
因为第3条数据在table2中没有关联.
这时使用左连接查询﹕
select table1.user_id,table1.user_name, table2.user_power
from table1,table2
where table1.user_id (+)= table2.user_id
或者是 left join on table1.user_id = table2.user_id
多个表 left join on table1.user_id = table2.user_id
left join on table1.user_id = table3.user_id
就可以得到如下的结果
user_id user_name user_power
1 aaa 000111
2 bbb 111000
3 ccc (null)
說明﹐左或右连接查询实际上是指定以那个标的数据为准﹐而默认(不指定左或右连接)是以两个表中都存在关联列的数据为准。
完全联接:返回左右联接的和集 select table1.user_id,table1.user_name, table2.user_power from table1 full (outer) join table2 on table1.user_id = table2.user_id;
交叉联接:没有where子句的交叉联接将产生联接所涉及表的笛卡尔积。第一个表的行数乘以第二个表的行数等于 笛卡尔积结果集的大小。select table1.user_id,table1.user_name, table2.user_power from table1 cross join table2(不带where条件)
如果交叉联接中带where的条件则和内联接一样。