右外连接在插入行后不起作用

Right Outer Join does not work after inserting row

我有 2 个 table 具有以下数据

ManualVersions - 所有手册版本的列表

+------------------+---------------+--------------+
|Id   | ManualID   | VersionNumber |  VersionName |
+-----+------------+---------------+--------------+
|10   |   12       |   1.0         |   Version 1  |
|17   |   12       |   2.0         |   Version 2  |

CustomersManuals - 这让我知道哪个客户可以访问哪些手册版本

+---+---------------+--------------------+
|Id | CustomerID    |  ManualVersionsID  |
+-- +---------------+--------------------+
|4  | 19            |     10             |
|8  | 24            |     10             |

目标是编写一个查询,让我知道客户可以访问和不能访问哪些手动版本。

为此我运行下面sql上面tables.

Select CustomersManuals.id as CustomerManualsID, ManualVersions.VersionNumber, ManualVersions.VersionName, ManualVersions.id as ManualVersionID
FROM CustomersManuals
RIGHT OUTER JOIN ManualVersions ON CustomersManuals.ManualVersionsID = ManualVersions.id
WHERE (CustomersManuals.CustomerID=24 OR CustomersManuals.CustomerID iS NULL) AND ManualVersions.ManualID = 12

上面的结果SQL

+-------------------+--------------+---------------+----------------+
|CustomerManualsID  | VersionNumber| VersionName   | ManualVersionID|
+-------------------+--------------+---------------+----------------+
| 8                 | 1.0          | Version 1     | 10             |
| NULL              | 2.0          | Version 2     | 17             |

以上正确,符合我的要求。返回 Null 显示 customerID 24 没有手册 2.

如果我现在将以下行插入 CustomersManuals table,上面的 SQL 将不起作用

CustomersManuals(我插入的行)

+----+------------+------------------+
| Id | CustomerID | ManualVersionsID |
+----+------------+------------------+
|30  | 18         | 17               |

以上sql现在只有returns1行

+-------------------+---------------+---------------+---------------------+
| CustomerManualsID | VersionNumber | VersionName   |   ManualVersionID   |
+-------------------+---------------+---------------+---------------------+
|  8                |  1.0          | Version 1     |   10                |

注意上面table CustomerManualsID 为空的行已经消失。

有没有办法显示客户拥有和没有的所有手册?

将条件放在 child table 的 ON 子句中,而不是 WHERE。那么你不需要明确测试 NULL.

Select CustomersManuals.id as CustomerManualsID, ManualVersions.VersionNumber, ManualVersions.VersionName, ManualVersions.id as ManualVersionID
FROM CustomersManuals
RIGHT OUTER JOIN ManualVersions ON CustomersManuals.ManualVersionsID = ManualVersions.id AND CustomersManuals.CustomerID=24
WHERE ManualVersions.ManualID = 12

DEMO

增补Barmar的回答,这样写会比较平常...

Select m.id CustomerManualsID
     , v.VersionNumber
     , v.VersionName
     , v.id ManualVersionID
  FROM ManualVersions v
  LEFT
  JOIN CustomersManuals m 
    ON m.ManualVersionsID = v.id 
   AND m.CustomerID = 24
 WHERE v.ManualID = 12