了解where子句vs连接

时间:2019-01-17 19:34:44

标签: sql join db2

有人可以解释以下查询示例之间的区别吗?

select column1,column2 
from table1 
join table2 
  on table1.columna = table2.columna 
  and columna='1234'

vs

select column1,column2 
from table1 
join table2 
  on table1.columna = table2.columna 
where columna='1234'

1 个答案:

答案 0 :(得分:1)

使用下表来回答您评论中的问题:

表1 表2

+---------+---------+    +---------+---------+ 
| column1 | columna |    | column2 | columna |
+---------+---------+    +---------+---------+
|      10 |    1234 |    |     100 |    1234 |
|      20 |    1234 |    |     200 |    5678 |
|      30 |    5678 |    +---------+---------+
|      40 |    9876 |
+---------+---------+

内部联接查询将产生:

+---------+---------+
| column1 | column2 |
+---------+---------+
|      10 |     100 |
|      20 |     100 |
+---------+---------+

on子句中包含过滤器的外部联接查询将产生:

+---------+---------+
| column1 | column2 |
+---------+---------+
|      10 |     100 |
|      20 |     100 |
|      30 |         |
|      40 |         |
+---------+---------+

而在联接之后带有过滤器的外部联接查询将产生:

+---------+---------+
| column1 | column2 |
+---------+---------+
|      10 |     100 |
|      20 |     100 |
+---------+---------+

请注意,由于两个表中都columna,因此您必须指明过滤器与哪个columna相关联。我假设是table1的。