【问题标题】:scala slick or and queryscala slick or 和查询
【发布时间】:2016-06-26 07:18:05
【问题描述】:

我的问题可能听起来很平淡,但我仍然没有解决它。

我的 Products Table 实现如下

class ProductsTable(tag: Tag) extends Table[Product](tag, "PRODUCTS") {
  def id = column[Int]("PRODUCT_ID", O.PrimaryKey, O.AutoInc)
  def title = column[String]("NAME")
  def description = column[String]("DESCRIPTION")
  def style = column[String]("STYLE")
  def price = column[Int]("PRICE")
  def category_id = column[Int]("CATEGORY_ID")
  def size_id = column[Int]("SIZE_ID")
  def brand_id = column[Int]("BRAND_ID")

  def * = (id.?, title, description, style, price, category_id, size_id, brand_id) <>(Product.tupled, Product.unapply _)
}

及其在

中的表示
val Products = TableQuery[ProductsTable]

如何实现与 SQl 查询等效的查询:

select * from products where( category_id = 1 or category_id = 2 or category_id = 3 ) and (price between min and max)

【问题讨论】:

    标签: scala slick


    【解决方案1】:

    试试这样的:

    val query = Products filter { p => (p.category_id inSet List(1,2,3)) && p.price > min && p.price < max }
    val result = db.run(query.result)
    

    您可以使用println(query.result.statements) 查看查询的样子。

    编辑

    回答其他问题。您可以为您的查询创建一个接受可选最小值和最大值的函数:

    def getProductsQuery(maybeMin: Option[Int] = None, maybeMax: Option[Int] = None) = {
      val initialQuery = val query = Products filter { p => (p.category_id inSet List(1,2,3)) }
      val queryWithMin = maybeMin match {
        case Some(min) => initialQuery filter { _.price > min }
        case None => initialQuery
      }
      val queryWithMax = maybeMax match {
        case Some(max) => queryWithMin filter { _.price < max }
        case None => queryWithMin 
      }
      queryWithMax
    }
    

    然后您可以执行以下任何操作:

    val q1 = getProductsQuery() // without min or max
    val q2 = getProductsQuery(maybeMin = Option(3)) // only min
    val q3 = getProductsQuery(maybeMax = Option(10)) // only max
    val q4 = getProductsQuery(maybeMin = Option(3), maybeMax = Option(10)) // both
    

    并根据需要运行其中任何一个...

    【讨论】:

    • 非常感谢......它正在工作,但我还有其他问题......有没有办法做同样的事情,但使用选项值,例如 min 和 max
    • 您可以在heremy blog post 中阅读有关查询的更多信息。
    • 当然,您也可以将您的 ids 列表作为参数.. :)
    猜你喜欢
    • 2012-12-21
    • 2012-10-17
    • 1970-01-01
    • 2017-04-06
    • 2021-03-20
    • 1970-01-01
    • 2020-09-18
    • 2016-11-21
    • 1970-01-01
    相关资源
    最近更新 更多