是否可以在普通的sql Slick中使用IN子句?

时间:2013-07-01 15:41:08

标签: scala scala-2.10 slick

例如,我想创建以下查询:

SELECT c.* FROM Coffees c WHERE c.name IN ('robusta', 'arabica')

我的尝试失败了:

val cnames = List("robusta", "arabica")
sql""" SELECT c.* FROM Coffees c WHERE c.name IN ${cnames} """
  could not find implicit value for parameter pconv: 
  scala.slick.jdbc.SetParameter[List[String]]

是否有可能在in普通sql查询中以某种方式使用Slick子句?

4 个答案:

答案 0 :(得分:32)

类型安全的“提升嵌入”API也支持这一点:

val ids = List(1,2,3)
val q = for {
  f <- Foo if f.id inSet ids // ids is not bound
}

slick.typesafe.com/doc/1.0.1/api/index.html#scala.slick.lifted.ColumnExtensionMethods

答案 1 :(得分:3)

我没有看到任何开箱即用的东西来处理这个问题。你最好的选择可能是这样的:

val cnames = List("robusta", "arabica").map("'" + _ + "'").mkString(",")
val query = sql""" SELECT c.* FROM Coffees c WHERE c.name IN (${cnames}) """

答案 2 :(得分:3)

尽管SQL注入不安全,但您可以使用#$插补器:

val ids = idList.map("'" + _ + "'").mkString(",")
val q = sql"""select name from mytable where id in (#$ids)"""

答案 3 :(得分:0)

有一个库(除其他外)为Slick的SQL插值器引入了用于列表属性的绑定器: https://index.scala-lang.org/tarao/slick-jdbc-extension-scala/slick-jdbc-extension

页面中的示例代码:

  import util.NonEmpty

  def findAll(entryIds: Option[NonEmpty[Long]]): Seq[Entry] = entryIds match {
    case Some(ids) => run { sql"""
    | SELECT * FROM ${table}
    | WHERE entry_id IN $ids
    """.as[Entry] }
    case None => Seq.empty
  }