right join :右连接,返回右表中所有的记录以及左表中连接字段相等的记录.
inner join: 内连接,又叫等值连接,只返回两个表中连接字段相等的行.
full join:外连接,返回两个表中的行:left join + right join
cross join:结果是笛卡尔积,就是第一个表的行数乘以第二个表的行数.
declare @a table(a int,b int)
declare @b table(a int,b int)
insert @a values(1,1)
insert @a values(2,2)
insert @b values(1,1)
insert @b values(3,3)
select * from @a
select * from @b
--左:
select * from @a Aa left join @b Bb on Aa.a=Bb.a
--右:
select * from @a Aa right join @b Bb on Aa.a=Bb.a
--内
select * from @a Aa inner join @b Bb on Aa.a=Bb.a
--外:
select * from @a Aa full join @b Bb on Aa.a=Bb.a
--交叉连接
select * from @a cross join @b
筛选条件放在left join on后面和放在where后面的结果不一样的。
记住on后面是连接条件,where后面是筛选条件就OK啦!
即:on后面的条件筛选参与连接的记录,主表中的记录会全部出现结果集中,而只有符合on条件的从表记录才会出现在结果集中。
SELECT A.ORDER_ID, B.TRANS_TYPE FROM GW_GATEWAY_ORDER A LEFT JOIN SYS_MCHT_SETTLE_DETAIL B ON A.ORDER_ID = B.ORDER_ID WHERE A.ORDER_ID >= 20101209150044021 AND A.ORDER_ID <= 20101210150048099;
结果:
ORDER_ID * TRANS_TYPE
20101209150044021 1
20101209150044021 2
20101210141359000 1
20101210144447001
SELECT A.ORDER_ID, B.TRANS_TYPE FROM GW_GATEWAY_ORDER A LEFT JOIN SYS_MCHT_SETTLE_DETAIL B ON A.ORDER_ID = B.ORDER_ID AND B.trans_type = 1 WHERE A.ORDER_ID >= 20101209150044021 AND A.ORDER_ID <= 20101210150048099;
结果:
ORDER_ID * TRANS_TYPE
20101209150044021 1
20101210141359000 1
20101210144447001
SELECT A.ORDER_ID, B.TRANS_TYPE FROM GW_GATEWAY_ORDER A LEFT JOIN SYS_MCHT_SETTLE_DETAIL B ON A.ORDER_ID = B.ORDER_ID WHERE A.ORDER_ID >= 20101209150044021 AND A.ORDER_ID <= 20101210150048099 AND B.trans_type = 1;
结果:
ORDER_ID * TRANS_TYPE
20101209150044021 1
20101210141359000 1