我想做一些与这些非常相似的事情:
可以让 PHP MYSQL 查询忽略 WHERE 子句中的空变量吗?
如果我作为子集的变量是,我希望忽略 where 子句NULL
。但是,我正在使用 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) )}
}
如果未指定,它会编写正确的where
语句行为,以及代码:p_id
dbGetQuery( con,paste0("select MIN(completion_date) from run ",write_pid_clause(p_id))))
这可以正常工作,但是,如果我想在 where 子句中插入更多条件,例如如果我想添加条件and status = 'complete'
when ,我会遇到困难p_id = NULL
。
有没有人对我如何在 R 中优雅地做到这一点有什么好主意?
编辑
这里有更多代码来演示我正在尝试做的事情,这是关于连接and
后的子句(这样做where
有点棘手)
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'"
>