2

示例数据的 SQL 小提琴链接

基本上我的疑问是,如果我们在LEFT OUTER JOIN的ON子句中指定条件,或者我们在WHERE 子句中使用空检查指定条件,是否相同?

表架构:

Create table App(ID number , STATUS varchar2(10));
Create table App_Child(child_id number ,
                       STATUS varchar2(10),
                       ID number );

查询 1

SELECT a.ID AS appID, a.STATUS AS appSTATUS,
b.child_id AS acOWNID,b.STATUS AS acSTATUS, b.id AS acID
 FROM App  a LEFT OUTER JOIN App_Child b ON (a.id=b.id AND b.STATUS <> 'disabled')  WHERE a.ID = ?;

查询 2

SELECT a.ID AS appID, a.STATUS AS appSTATUS,
b.child_id AS acOWNID,b.STATUS AS acSTATUS, b.id AS acID
 FROM App  a LEFT OUTER JOIN App_Child b ON (a.id=b.id)  WHERE a.ID = ? AND (b.STATUS IS NULL OR b.STATUS<>'disabled');
4

1 回答 1

3

结果和可读性都不一样。

  • 当您在on子句中编写条件时,您将包含 App 中的所有行。
  • 当您在where子句中编写条件时,您会从结果中过滤行:

在您的情况下,App与带有 b.STATUS='disabled' 的 App_Child 相关的行将被过滤

这是一个示例:

INSERT INTO App VALUES(1,'active');

INSERT INTO App_Child VALUES(3,'disabled',1);

SELECT a.ID AS appID, a.STATUS AS appSTATUS,
b.child_id AS acOWNID,b.STATUS AS acSTATUS, b.id AS acID
 FROM App  a LEFT OUTER JOIN App_Child b 
      ON (a.id=b.id AND b.STATUS <> 'disabled')  
WHERE a.ID = 1;

--- has results ---

SELECT a.ID AS appID, a.STATUS AS appSTATUS,
b.child_id AS acOWNID,b.STATUS AS acSTATUS, b.id AS acID
 FROM App  a LEFT OUTER JOIN App_Child b ON (a.id=b.id)  
WHERE a.ID = 1 AND (b.STATUS IS NULL OR b.STATUS<>'disabled');

-- don't has results --
于 2013-01-09T10:25:27.607 回答