oracle--left join and 和left join where的區別

開發程序時,常常會遇到left join,inner join的語句,Join是關係型數據庫系統的重要操做之一,相對來講速度要快一些,因此你們通常都會優先選擇join語句。

     可是在作程序時,對於join的一些用法卻不必定很清晰。今天給你們講的是left join and 和left join where。 數據庫

     數據庫在經過鏈接兩張或多張表來返回記錄時,都會生成一張中間的臨時表,而後再將這張臨時表返回給用戶。 開發

     在使用left jion on時,and和where條件的區別以下: 數學

     一、 on條件是在生成臨時表時使用的條件,它無論on中的條件是否爲真,都會返回左邊表中的記錄,and只會過濾掉B表中的記錄。B表中不符合條件的部分所有被設置爲null。 it

     二、where條件是在臨時表生成好後,再對臨時表進行過濾的條件。這時已經沒有left join的含義(必須返回左邊表的記錄)了,條件不爲真的就所有過濾掉。 io

 

    示例: table

建表語句: 基礎

      create table tmp_lxq_1
(
  id varchar2(10),
  name varchar2(20)
);
insert   into tmp_lxq_1
select '1','張三' from dual;
insert   into tmp_lxq_1
select '2','李四' from dual;
insert   into tmp_lxq_1
select '3','王五' from dual;
commit; select

tmp_lxq_1表結果: 搜索

ID NAME
1 張三
2 李四
3 王五 程序

drop table tmp_lxq_2;
create table tmp_lxq_2
(
  id varchar2(10),
  subject varchar2(30),
  score varchar2(30)
);

insert   into tmp_lxq_2
select '1','語文','80' from dual;
insert   into tmp_lxq_2
select '2','數學','90' from dual;
insert   into tmp_lxq_2
select '4','英語','60' from dual;
commit;

tmp_lxq_2結果:

ID SUBJECT SCORE
1 語文 80
2 數學 90
4 英語 60

而後運行下面幾個語句:

1.inner join

inner jion 取A表和B表的交集,無論A表在左仍是B表在左。

 

select a.id,a.name,b.id,b.subject,b.score from tmp_lxq_1 a
inner join tmp_lxq_2 b
on a.id=b.id;

結果:

ID NAME ID SUBJECT SCORE
1 張三 1 語文 80
2 李四 2 數學 90

 

2.left join 

left join 是以A表的記錄爲基礎的,A能夠當作左表,B能夠當作右表,left join是以左表爲準的。換句話說,左表(A)的記錄將會所有表示出來,而右表 (B)只會顯示符合搜索條件的記錄(例子中爲: A.ID = B.ID)。B表記錄不足的地方均爲NULL。
 

select a.id,a.name,b.id,b.subject,b.score from tmp_lxq_1 a
left join tmp_lxq_2 b
on a.id=b.id;

1 張三 1 語文 80
2 李四 2 數學 90
3 王五   


3.left join and

left join and 也是以A表的記錄爲基礎的,A能夠當作左表,B能夠當作右表,left join and是以左表爲準的。換句話說,左表(A)的記錄將會所有表示出來, 而右表(B)只會顯示符合搜索條件的記錄(例子中爲: A.ID = B.ID)。B表記錄不足的地方均爲NULL,加上and條件後,A表記錄也將所有 被表示出來,而B表只會將符合條件的記錄顯示出來,B表記錄中不符合條件的地方均顯示爲null。

 

select a.id,a.name,b.id,b.subject,b.score from tmp_lxq_1 a
left join tmp_lxq_2 b
on a.id=b.id
and b.score>=80;

ID NAME ID SUBJECT SCORE
1 張三 1 語文 80
2 李四 2 數學 90
3 王五   


4.left join where 

left join where條件是在臨時表生成好後,再對臨時表進行過濾的條件。這時已經沒有left join的含義(必須返回左邊表的記錄)了,條件不爲真的就所有過濾掉。
 

select a.id,a.name,b.id,b.subject,b.score from tmp_lxq_1 a
left join tmp_lxq_2 b
on a.id=b.id
where b.score>=80;

ID NAME ID SUBJECT SCORE 1 張三 1 語文 80 2 李四 2 數學 90

相關文章
相關標籤/搜索