Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
mysql中的where子句为空(当我使用RMySql dbGetQuery时)_Mysql_Sql_R_Rmysql - Fatal编程技术网

mysql中的where子句为空(当我使用RMySql dbGetQuery时)

mysql中的where子句为空(当我使用RMySql dbGetQuery时),mysql,sql,r,rmysql,Mysql,Sql,R,Rmysql,我想做一些真正类似的事情: 如果我设置子集的变量为NULL,我希望忽略where子句。但是,我使用dbGetQuery从R访问MySQL数据库。到目前为止,我有这样的代码 write_pid_clause = function(p_id=NULL){ if(is.null(p_id)){return(NULL)} else {return(paste0("where project_id = ",p_id) )} } 如果未指定p_id,则写入正确的,其中语句行为,以及代码: d

我想做一些真正类似的事情:

如果我设置子集的变量为
NULL
,我希望忽略where子句。但是,我使用dbGetQuery从R访问MySQL数据库。到目前为止,我有这样的代码

write_pid_clause = function(p_id=NULL){
 if(is.null(p_id)){return(NULL)}
 else {return(paste0("where project_id = ",p_id)  )}
}
如果未指定
p_id
,则写入正确的
,其中
语句行为,以及代码:

  dbGetQuery( con,paste0("select MIN(completion_date) from run ",write_pid_clause(p_id))))
但是,如果我希望在where子句中插入更多条件,例如,如果我想在
p\u id=NULL
时添加条件
和状态='complete'
,这将正常工作

有人对我如何在R中优雅地做到这一点有什么好的想法吗

编辑 这里有更多的代码来演示我要做的事情,这是关于连接后的
子句(执行
其中
有点棘手)

make_和_子句=函数(p_id=,start_date=,end_date=){
条件=列表(
列表(“和r.project_id=”,p_id“”,
列表(“和r.完成日期>=”,开始日期“”,

名单("r.completion\u date='3'和r.completion\u date='3'和r.completion\u date我认为没有一种简单明了的方法可以实现您想要的。如果您想添加多个子句,每个子句都依赖于一个变量的内容,那么您必须构建每个子句。我能想到的唯一相关SQL技巧是将
放在其中1=1
在SQL语句中,然后为每个值添加
和column=value


我看到@Marek提供了一个带有代码的答案;也许您可以将这些答案结合起来生成一个可行的解决方案。

从您的函数开始,我提出了如下建议:


make_和_子句
status
也可以为空。此外,where子句可能包含两个以上的条件检查,因此编写所有可能的if子句变得不切实际。我认为没有一种简单明了的方法来实现您的目标。如果您希望能够添加多个子句,每个子句都取决于上下文对于一个变量,您必须构建每个变量。我能想到的唯一相关SQL技巧是在SQL语句中放入
其中1=1
,然后为每个值添加
和column=value
。这样,如果您不使用一个变量,语法仍然正确。您好,这听起来真的很好。请参阅我为处理mult编写的新代码I删除缺失的案例。在这种情况下,
Where 1=1
命令正是我处理必须使用
Where
的案例所需要的。如果您将其作为答案发布,我将向上投票:)谢谢。这正是我所需要的,不用求助于
where 1=1
。我特别喜欢使用
!missing
sprintf
。现在将第一批代码转换为可以处理任意参数列表的代码。类似于
lappy(as.list)(args(make\u和_子句),function(arg){if(!missing(arg))sprintf(arg,eval(arg)})
。。。
make_and_clauses = function(p_id = "",start_date="", end_date=""){

 conditions = list(
   list(" and r.project_id ='", p_id,"'"),
   list(" and r.completion_date >= '",start_date,"'"),
   list(" and r.completion_date <= '", end_date, "'"))
 condition_values = c(p_id,start_date, end_date)
 conditions[which(condition_values =="")] <- ""
 conditions = unlist(conditions,recursive=TRUE)
 paste0(conditions,collapse="")

}
> make_and_clauses(2,3,4)
[1] " and r.project_id ='2' and r.completion_date >= '3' and r.completion_date <= '4'"
> make_and_clauses(2,,4)
[1] " and r.project_id ='2' and r.completion_date <= '4'"
> make_and_clauses(,3,2)
[1] " and r.completion_date >= '3' and r.completion_date <= '2'"

>