生产环境_使用Scala语言_Spark编写灵活的SQL查询生成器

 // 判断id是否为空
 val idEmpty = id.isEmpty
 // 判断other是否为空
 val otherEmpty = other.isEmpty

 // 根据不同情况拼接SQL语句
 val sql = if (idEmpty) {
   // 如果id为空
   if (otherEmpty) {
     // 如果other也为空
     s"""select * from `$table1` where `$time` between '$startTime' and '$endTime'"""
   } else {
     // 如果other不为空
     val otherStr = otherArr.map("\"" + _ + "\"").mkString("(",",",")")
     s"""select * from `$table2` where `$time` between '$startTime' and '$endTime' and $otherCol in $otherStr"""
   }
 } else {
   // 如果id不为空
   if (otherEmpty) {
     // 如果other为空
     val selectStr = mbArr.map("\"" + _ + "\"").mkString("(",",",")")
     s"""select * from `$table1` where `$time` between '$startTime' and '$endTime' and $idCol in $selectStr"""
   } else {
     // 如果other不为空
     val selectStr = mbArr.map("\"" + _ + "\"").mkString("(",",",")")
     val otherStr = otherArr.map("\"" + _ + "\"").mkString("(",",",")")
     s"""select * from `$table2` where `$time` between '$startTime' and '$endTime' and $idCol in $selectStr and $otherCol in $otherStr"""
   }
 }

//https://blog.csdn.net/qq_52128187?type=blog
//by20231214_matrix70

 println(sql)
根据输入的条件动态构建SQL查询语句

你可能感兴趣的:(SQL,数据分析与处理,Spark,scala,spark,sql)