SQL INNER JOIN 与带 WHERE 的 LEFT JOIN

SQL INNER JOIN vs LEFT JOIN with a WHERE

我试图更直观地掌握 SQL 连接。就在昨天,我了解了如何将 RIGHT JOIN 重写为 LEFT JOIN(通过翻转表的顺序),这帮助我更好地理解了两个连接的工作方式。

但是,现在我想知道是否可以将 INNER JOIN 重写为具有 WHERE 条件的 LEFT JOIN - 这意味着它们的逻辑可能是等效的("logic" 我不是说执行计划,而是描述预期结果集的方式)。

喜欢:

SELECT * FROM HeaderTable
INNER JOIN DetailTable 
ON HeaderTable.ID = DetailTable.ParentID

我会读作 "Show me all the records from tables HeaderTable and DetailTable that have a matching value in the HeaderTable.ID and DetailTable.ParentID fields." 与以下内容相同:

SELECT * FROM HeaderTable
LEFT JOIN DetailTable 
ON    HeaderTable.ID = DetailTable.ParentID
WHERE HeaderTable.ID = DetailTable.ParentID

我会读作 "Show me all the records from tables HeaderTable and DetailTable where the value of HeaderTable.ID is the same as the value of DetailTable.ParentID."

请问这些return是同一个结果集吗?我更想问的是逻辑相同,而不是一个比另一个更有效。

如果我可能会问,请不要用任何维恩图来回答,因为这些似乎并没有向我准确描述连接的逻辑。

是的,他们会return相同的结果。

但是你可以简单地写

SELECT * 
FROM HeaderTable, DetailTable
WHERE HeaderTable.ID = DetailTable.ParentID

这return也是同样的结果。这是引入 join-clauses 之前使用的旧语法。

是的,他们会return相同的结果。没有 where 子句的左连接将读作 show me all records from the header table and the related items from the details table 或 null for the details where没有匹配项

添加与 ID 相关的 where 子句通过消除 non-matching 行,这些行将显示为具有详细信息部分的空值,从而有效地将左联接转换为内部联接。

在某些数据库中,例如 MS SQL Server,左连接会在查询执行计划中显示为内部连接。

虽然你说你不想要维恩图,但我还是忍不住向你推荐 this question and its answers,即使它们充满了(我认为非常有用的)维恩图。

在左连接中,如果您在 where 中引用左侧,则您否定左侧并将其变成常规连接