#######創建表1並添加
#####在hr/hr@pdbs 連接後創建
create table test1
( code varchar2(10),
id varchar2(20) not null
);
alter table test1 add constraint pk_m1 primary key(id);
創建表2並增加主鍵約束
create table test2
(
code varchar2(10),
id varchar2(20) not null
);
alter table test2 add constraint pk_m2 primary key(id);
####插入數據
insert into test1 values('1001','2001');
insert into test1 values('1002','2002');
insert into test2 values('1002','2002');
insert into test2 values('1003','2003');
insert into test2 values('1004','2004');
commit;
一、自然連接 (natural join)
相同值才顯示
語法: 表1 join 表2 on 1.xxx=b.xxx 或者 表1,表2 where 1.xxx=2.xxx
SQL> select a.code t_test1,b.code t_test2 from test1 a join test2 b on a.id=b.id;
T_TEST1 T_TEST2
---------- ----------
1002 1002
1 row selected.
二、自連接(self join)
自連接(self join)是SQL語句中經常要用的連接方式,
使用自連接可以將自身表的一個鏡像當作另一個表來對待,從而能夠得到一些特殊的數據
SQL> select a.code t_test1,b.code t_test2 from test1 a join test1 b on a.id=b.id;
T_TEST1 T_TEST2
---------- ----------
1001 1001
1002 1002
2 rows selected.
三、外連接(outer join)的幾種方式:
1、left outer (左連接):
左側的表中的全部數據都會被顯示出來,但是右側表的數據,
只有和左側匹配上的字段纔會被查詢出來!否則都會顯示null!
語法: 表1 left join 表 2 on 1.xxx=2.xxx 或者 表1,表2 where 1.xxx=2.xxx(+) 2表示匹配表相同方式,
eg:
SQL> select a.code t_test1,b.code t_test2 from test1 a left join test2 b on a.id=b.id;
T_TEST1 T_TEST2
---------- ----------
1001
1002 1002
2 rows selected.
2、right outer(右連接):
右側的表中的全部數據都會被顯示出來,但是左側表的數據,
只有和右側匹配上的字段纔會被查詢出來!否則都會顯示null!
語法: 表1 right join 表 2 on 1.xxx=2.xxx 或者 表1,表2 where 1.xxx(+)=2.xxx 2表示匹配表相同方式,
eg:
SQL> select a.code t_test1,b.code t_test2 from test1 a right join test2 b on a.id=b.id;
T_TEST1 T_TEST2
---------- ----------
1002 1002
1003
1004
3 rows selected.
四、交叉連接(cross join):
表與表之間做笛卡爾積查詢(數學裏面的組合形式):千萬不要出現這種情況(不會使用這種)
select * from table1 cross join table 2 ;
SQL> select * from test1 cross join test2;
CODE ID CODE ID
---------- -------------------- ---------- --------------------
1001 2001 1002 2002
1001 2001 1003 2003
1001 2001 1004 2004
1002 2002 1002 2002
1002 2002 1003 2003
1002 2002 1004 2004
已選擇 6 行。