---
title: "left join where on区别"
author: "slnddd"
date: "2019-05-08T09:56:36Z"
tags: []
categories: ["数据库"]
slug: "left-join-where-on"
draft: false
lastmod: "2019-05-08T09:56:36Z"
id: 2440733
url: "https://slnddd.iteye.com/blog/2440733"
---

在使用left jion时，on和where条件的区别如下：

1、 on条件是在生成临时表时使用的条件，它不管on中的条件是否为真，都会返回左边表中的记录。

2、where条件是在临时表生成好后，再对临时表进行过滤的条件。这时已经没有left join的含义（必须返回左边表的记录）了，条件不为真的就全部过滤掉。

 

 

表1：tab2

id

size

1

10

2

20

3

30

表2：tab2

size

name

10

AAA

20

BBB

20

CCC

两条SQL:  
1、select * form tab1 left join tab2 on (tab1.size = tab2.size) where tab2.name=’AAA’  
2、select * form tab1 left join tab2 on (tab1.size = tab2.size and tab2.name=’AAA’)

 

 

SQL1 :

 

1、中间表 on条件: tab1.size = tab2.size

 

tab1.id

tab1.size

tab2.size

tab2.name

1

10

10

AAA

2

20

20

BBB

2

20

20

CCC

3

30

(null)

(null)

 

2、再对中间表过滤 where 条件： tab2.name=’AAA’

tab1.id

tab1.size

tab2.size

tab2.name

1

10

10

AAA

 

 

SQL2 :

 

中间表on条件: tab1.size = tab2.size and tab2.name=’AAA’(条件不为真也会返回左表中的记录)

tab1.id

tab1.size

tab2.size

tab2.name

1

10

10

AAA

2

20

(null)

(null)

3

30

(null)

(null)