左连接select * from t1 left join t2 on t1.no=t2.no/*测试结果*/ id no cou price no -------------------------------------------------------------------------------------- apple 1 100 1.0 1 bananer 2 200 NULL NULL orange 3 400 3.0 3 右连接select * from t1 right join t2 on t1.no=t2.no /*测试结果*/ id no cou price no -------------------------------------------------------------------------------------- apple 1 100 1.0 1 orange 3 400 3.0 3
晕!看的不清楚啊!左id no cou price no -------------------------------------- apple 1 100 1.0 1 bananer 2 200 NULL NULL orange 3 400 3.0 3 右id no cou price no -------------------------------------- apple 1 100 1.0 1 orange 3 400 3.0 3
--关于连接的简单示例--测试数据 declare @a table(ida int) insert @a select 1 union all select 2declare @b table(idb int) insert @b select 2 union all select 3--内连接 select * from @a a join @b b on a.ida=b.idb/*--测试结果 只返回两个表中ida与idb相同的记录 ida idb ----------- ----------- 2 2(所影响的行数为 1 行) --*/ --左连接 select * from @a a left join @b b on a.ida=b.idb/*--测试结果 返回@a(左边表)所有的记录,及@b的idb与@a的ida对应的记录 没有对应的就用null表示ida idb ----------- ----------- 1 NULL 2 2(所影响的行数为 2 行) --*/ --右连接 select * from @a a right join @b b on a.ida=b.idb/*--测试结果 返回@b(右边表)所有的记录,及@b的idb与@a的ida对应的记录 没有对应的就用null表示ida idb ----------- ----------- 2 2 NULL 3(所影响的行数为 2 行) --*/ --全连接 select * from @a a full join @b b on a.ida=b.idb/*--测试结果 返回@a与@b的所有记录,没有对应的用NULL表示ida idb ----------- ----------- 2 2 NULL 3 1 NULL(所影响的行数为 3 行) --*/
id no cou price no
--------------------------------------------------------------------------------------
apple 1 100 1.0 1
bananer 2 200 NULL NULL
orange 3 400 3.0 3
右连接select * from t1 right join t2 on t1.no=t2.no
/*测试结果*/
id no cou price no
--------------------------------------------------------------------------------------
apple 1 100 1.0 1
orange 3 400 3.0 3
--------------------------------------
apple 1 100 1.0 1
bananer 2 200 NULL NULL
orange 3 400 3.0 3
右id no cou price no
--------------------------------------
apple 1 100 1.0 1
orange 3 400 3.0 3
declare @a table(ida int)
insert @a select 1
union all select 2declare @b table(idb int)
insert @b select 2
union all select 3--内连接
select * from @a a join @b b on a.ida=b.idb/*--测试结果
只返回两个表中ida与idb相同的记录
ida idb
----------- -----------
2 2(所影响的行数为 1 行)
--*/
--左连接
select * from @a a left join @b b on a.ida=b.idb/*--测试结果
返回@a(左边表)所有的记录,及@b的idb与@a的ida对应的记录
没有对应的就用null表示ida idb
----------- -----------
1 NULL
2 2(所影响的行数为 2 行)
--*/
--右连接
select * from @a a right join @b b on a.ida=b.idb/*--测试结果
返回@b(右边表)所有的记录,及@b的idb与@a的ida对应的记录
没有对应的就用null表示ida idb
----------- -----------
2 2
NULL 3(所影响的行数为 2 行)
--*/
--全连接
select * from @a a full join @b b on a.ida=b.idb/*--测试结果
返回@a与@b的所有记录,没有对应的用NULL表示ida idb
----------- -----------
2 2
NULL 3
1 NULL(所影响的行数为 3 行)
--*/
左联时,会全显左表的数据,如果右表没有满足的条件的数据为Null.
右联时,会全显右表的数据,如果左表没有满足的条件的数据为Null.