数据库查询语句的左连接和右连接

左连接和右连接都是外部连接,也就是区别于内部连接,它对不满足连接条件的行,并不是象内部连接一样将数据完全过滤掉,而是保留一部分数据,行数不会减少。

内部连接是两个表中都必须有连接字段的对应值的记录,数据才能检索出来

左连接是只要左边表中有记录,数据就能检索出来,而右边有的记录必要在左边表中有的记录才能被检索出来

右连接是只要右边表中有记录,数据就能检索出来

 

 

左连接就是以左边的表记录为主,右连接就是以右边的表记录为主

create table table1(
        user_id int primary key,
        user_name varchar(20),
        user_pass varchar(20)
);

create table table2(
	user_id int primary key,
        user_power  varchar(20)
);

insert into table1 values(1,'aaa','aaa');
insert into table1 values(2,'bbb','bbb');
insert into table1 values(3,'ccc','ccc');

insert into table2 values(1,'111');
insert into table2 values(2,'222');

select table1.user_id,table1.user_name,table2.user_power from table1,table2 where table1.user_id = table2.user_id;

左连接
sql server中
select table1.user_id,table1.user_name,table2.user_power from table1,table2 where table1.user_id(+) = table2.user_id;
mysql中
select table1.user_id,table1.user_name,table2.user_power from table1 left join table2 on table1.user_id = table2.user_id;

上面是测试sql语句,自己可以试一试


有兩個表

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

但是這樣檢索到的數據只有兩條:

user_id       user_name        user_power

       1             aaa              000111

       2             bbb              111000

因為第三條數據在table2中沒有關聯.

 

這時使用左連接查詢﹕

select table1.user_id,table1.user_name,table2.user_power

from table1,table2

where table1.user_id (+)= table2.user_id

就可以得到如下的結果

user_id       user_name        user_power

       1             aaa              000111

       2             bbb              111000

       3             ccc              (null)

說明﹐左或右連接查詢實際上是指定以哪個表的數據為准﹐而默認(不指定左或右連接)是以兩個表中都存在關鍵列的數據的為准。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值