sqldf 中的 LEFT JOIN 不适当地过滤 WHERE 条件

问题描述 投票:0回答:1

我正在使用 sqldf 将数据字典左连接到响应字段。我想创建一个条件,仅当某些字段不为空时才加入,但我不想想过滤掉这些字段(这就是为什么我首先要做左连接!)。没有 WHERE 条件,一切都很好:

screening_data_responses_test <- sqldf("select *
      FROM screening_data_responses v
      LEFT JOIN data_dictionary_qonly i 
                       on i.lql_id=v.question_id")

但是当我添加 WHERE 条件时,它会过滤掉所有不满足 WHERE 条件的行:

screening_data_responses_test <- sqldf("select *
      FROM screening_data_responses v
      LEFT JOIN data_dictionary_qonly i 
                       on i.lql_id=v.question_id
                       WHERE v.response_char IS NOT NULL or v.response_num IS NOT NULL")

我知道 WHERE 位于错误的位置,并且它是在连接发生后应用的,这就是它被过滤的原因。但我不知道该把它移到哪里或者我应该用什么来代替。如何修改我的代码,以便 v.response_char 和 v.response_num 中带有空值的行不被加入,而是保留在数据帧中(data_dictionary_qonly 的相应列中带有空值)?

r sqldf
1个回答
0
投票

通常的做法是将条件从 WHERE 子句移至 JOIN 子句:

screening_data_responses_test <- sqldf("select *
  FROM screening_data_responses v
  LEFT JOIN data_dictionary_qonly i 
         ON i.lql_id=v.question_id
        AND v.response_char IS NOT NULL 
        AND v.response_num IS NOT NULL
")

(未经测试,我没有现成的 R 安装)

© www.soinside.com 2019 - 2024. All rights reserved.