连接两个表以保留选定的值和空值

Joining two tables to keep selected values and nulls

我有两个 table 需要加入。第二个 table 用于过滤第一个 table.

的记录

结果应包括 table1 中某个 parameter_group 的所有记录,但也包括参数为空的记录。
我有的是:

table1 LEFT JOIN table2  
ON table1.parameter=table2.parameter  
WHERE table2.parameter_group IS 'A' OR table1.parameter IS NULL

我的问题是 - 这是实现目标的最有效方法吗?重点是每个过滤器(parameter_group IS 'A' OR table1.parameter IS NULL)仅针对非常大的 table1 中的百分之几的记录。 我认为这是关于澄清(向我解释)处理顺序...感谢您的帮助。

如果您想要 table1 中的所有行以及 table2 中与 parameter_group = 'A' 的匹配项,则将条件移动到 ON:

table1 LEFT JOIN
table2  
ON table2.parameter = table1.parameter  AND
   table2.parameter_group = 'A' 

你的方法并不总是奏效。如果table2有一个参数是不是'A',那么它会被过滤掉

所以你想要 table1.parameter IS NULL 的所有行加上 table1.parameter 匹配表 2 中具有 table2.parameter_group='A'?[=11= 的行的所有行]

table1 LEFT JOIN table2  
ON table1.parameter=table2.parameter /* matching condition */
  AND table2.parameter_group = 'A' /* only try to match these rows */
WHERE table1.parameter IS NULL /* keep rows with NULL from table1 */
  OR table2.parameter IS NOT NULL /* plus keep matched rows */