資料庫 連線(自然連線 外連線 內連線)

2021-09-09 07:56:32 字數 2892 閱讀 3544

1、自然連線:只考慮那些在兩個關係模式中都出現的屬性上取值相同的元組對natural joinjoin...using

select a1,a2,...,an

from r1 natural join r2 natural join ... natural join rn

where p;

select name1, course_id

from instructor, teaches

where instructor.id = teaches.id;

等價於

select name1, course_id

from instructor natural join teaches;

### 但以下的乙個例子卻不等價 ###

前提:已知instructor和teaches自然連線包括屬性(id, name, dept_name, salary, course_id, sec_id)

而course關係包含的屬性是(course_id, title, dept_name, credits)

select name,title

from instructor natural join teaches, course

where teaches.course_id = course.course_id;

-- 列出教師的名字以及他們所講授課程的名稱

不等價於

select name1,title

from instructor natural join teaches natural join course;

原因:instructor、teaches和course三者自然連線包括屬性(course_id, dept_name)

而instructor和teaches自然連線後,再讓teaches與course根據屬性course_id相同選出元組的結果,會忽略掉所有(course_id, dept_name)這樣的對,因此兩種查詢結果不同

因此,為了發揚自然連線的優點,同時避免不必要的相等的屬性帶來的危險,引入了下面的構造形式 

select a1,a2

from r1 join r2 using (a1,a3); -- r1、r2為表名

join...using與自然連線相似,但可以指定用哪些屬性進行匹配連線,在t1.a1 = t2.a1並且t1.a2 = t2.a2成立的前提下(t1、t2為元組),來自r1的元組t1和來自r2的元組t2就能匹配,即使r1和r2都具有名為a3的屬性,也不需要t1.a3 = t2.a3成立

on條件:允許在參與連線的關係上設定通用的謂詞,可表示任何sql謂詞

on中謂詞的寫法與where子句謂詞類似;與using條件一樣,on條件出現在連線表示式的末尾

select *

from student join takes on student.id = takes.id;

2、外連線(outer join):保留那些在連線中丟失的元組

左(右)側關係中不匹配右(左)側關係任何元組的元組被添上空值並加入到結果中

select *

from student natural left outer join takes;

-- -----------------------------------------

select *

from takes natural right outer join student;

-- -----------------------------------------

-- 以上兩個得到的結果是一樣的,只不過結果中屬性出現的順序不同

在外連線中,on和where的表現是不同的。原因是外連線只為那些對相應內連線結果沒有貢獻的元組補上空值並加入結果。

select *

from student left outer join takes on student.id = takes.id;

不等價於

select * 

from student left outer join takes on true

where student.id = takes.id;

3、內連線(inner join):不保留未匹配元組的連線運算

join子句中沒有使用outer字首,預設連線型別是inner join,常規連線為內連線

select *

from student join takes using(id);

等價於

select *

from student inner join takes using(id);

類似地,natural join等價於natural inner join

4、任意的連線形式/型別(內連線、左外連線、右外連線、全外連線)可以和任意的連線條件(自然連線natural、using條件連線或on條件連線)進行組合

mysql資料庫外連線,內連線,自然連線

create table join teacher id int primary key auto increment,t name varchar 10 not null,gender enum male female secret not null engine innodb character...

資料庫中的內連線 自然連線 外連線

資料庫中的內連線 自然連線 外連線 資料中的連線join分為內連線 自然連線 外連線,外連線又分為左外連線 右外連線 全外連線。當然,這些分類都是在連線的基礎上,是從兩個表中記錄的笛卡爾積中選取滿足連線的記錄。笛卡爾積簡單的說就是乙個表裡的記錄要分別和另外乙個表的記錄匹配為一條記錄,即如果表a有3條...

資料庫左連線,右連線,內連線,外連線

首先連線有 內連線,外連線 左外,右外 全連線 交集 交叉連線 笛卡爾積 先略兩個表 尷尬,join打錯了,畢竟英語沒有6級 解釋下就是以左邊表id 案例裡面是test1 為基礎和右表id對比,左表有的右表也有就也出來,右表沒有的就null咯,右連線和左連線相反 enh,以右邊表id為基礎和左邊表i...