在以下两个sql查询sql1
中未选择任何行,sql2
仅为111@k2.com
选择1
var ids="'111@k2.com','222@k2.com','333@k2.com','444@k2.com','555@k2.com','666@k2.com'"
val sql1 = SQL("SELECT id,point,privacy FROM `pointTable` WHERE state=1 and id in ({users})").on("users" -> ids)
sql1().map { row =>
val point = if (row[Boolean]("privacy")) { row[Double]("point").toString } else { "0" }
println(write(Map("id" -> row[String]("id"), "point" -> point)))
}
val sql2 = SQL("SELECT id,point,privacy FROM `pointTable` WHERE state=1 and id in (" + ids + ")")
sql2().map { row =>
val point = if (row[Boolean]("privacy")) { row[Double]("point").toString } else { "0" }
println(write(Map("id" -> row[String]("id"), "point" -> point)))
}
在phpmyadmin中,当我运行此查询时,它会返回6行,然后为什么不能在这里完美运行。 我正在使用Play框架2.2与scala 2.1
答案 0 :(得分:1)
那不行。传递users
虽然on
将转义整个字符串,因此它将显示为一个值而不是列表。 Play 2.3中的Anorm实际上允许您将列表作为参数传递,但在这里您必须解决这个问题。
val ids: List[String] = List("111@k2.com", "222@k2.com", "333@k2.com")
val indexedIds: List[(String, Int)] = ids.zipWithIndex
// Create a bunch of parameter tokens for the IN clause.. {id_0}, {id_1}, ..
val tokens: String = indexedIds.map{ case (id, index) => s"{id_${index}}" }.mkString(", ")
// Create the parameter bindings for the tokens
val parameters = indexedIds.map{ case (id, index) => (s"id_${index}" -> toParameterValue(id)) }
val sql1 = SQL(s"SELECT id,point,privacy FROM `pointTable` WHERE state=1 and id in (${tokens})")
.on(parameters: _ *)