可是在作程序時,對於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
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
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
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