資料表的串連有:
1、內串連(自然串連): 只有兩個表相匹配的行才能在結果集中出現
2、外串連: 包括
(1)左外串連(左邊的表不加限制)
(2)右外串連(右邊的表不加限制)
(3)全外串連(左右兩表都不加限制)
3、自串連(串連發生在一張基表內)
sql標準文法:
select table1.column,table2.column
from table1 [inner | left | right | full ] join table2 on table1.column1 = table2.column2;
inner join 表示內串連;left join表示左外串連;right join表示右外串連;full join表示完全外串連;
on子句用於指定串連條件。注意,如果使用from子句指定內、外串連,則必須要使用on子句指定串連條件;
如果使用(+)操作符指定外串連,則必須使用where子句指定串連條件。
如果主表的主鍵列和從表的外部鍵列名稱相同,那麼可以使用 natural join 關鍵字自動執行內串連操作。
select dname,ename from dept natural join emp;
舉例說明:有兩張表(students、classes)
create table students(studentno number, studentname varchar2(20), classname varchar2(20))
create table classes(id number, classname varchar2(20));
1)左外串連:
當以上兩表的資料分別為
students表:
classes表
執行以下左外串連語句:
select a.studentno, a.studentname, b.classname
from students a, classes b
where a.classid = b.classid(+);
結果:
注釋:左連結則左邊表的資料會全部顯示
2)右外串連:
當以上兩表的資料分別為
students表:
classes表:
執行以下右外串連語句:
select a.studentno, a.studentname, b.classname
from students a, classes b
where a.classid(+) = b.classid;--注意此處(+)的位置,右外串連在左邊,即相反的位置
結果:
注釋:右連結則右邊表的資料會全部顯示
3)自然連結
以上兩種表的資料情況下,執行以下自然連結語句,結果都一樣:
select a.studentno, a.studentname, b.classname
from students a, classes b
where a.classid = b.classid;
結果:
總之,
左串連顯示左邊全部的和右邊與左邊相同的
右串連顯示右邊全部的和左邊與右邊相同的
內串連是只顯示滿足條件的!