【问题标题】:How would I perform this SQL query with subselect in Slick?我将如何在 Slick 中使用 subselect 执行此 SQL 查询?
【发布时间】:2021-01-29 23:12:40
【问题描述】:
select
    *,
    (select count(1) from variants as v where v.product_id = p.id) as variants
from
    products as p
;

查询给出了我想要的结果,所以我现在只需要能够从 Slick 上做同样的事情。我有 ProductVariant 模型与相应的 ProductsVariants 表和 productsvariants TableQuerys 设置。

这就是我最终的结果:

products.map(product =>
            (product, variants.filter(_.productId === product.id).length)
        ) map (_ <> (ProductAndVariantCount.tupled, ProductAndVariantCount.unapply))

【问题讨论】:

标签: sql postgresql scala subquery slick


【解决方案1】:

基本形式是:

products.map(row => 
  (row.id, row.otherColumnsHere, variants.filter(_.product_id === row.id).length)
)

我解决这些问题的方法是将查询的每个部分转换为 Slick 表达式,然后看看它们如何组合。

你的想法是:

  • 子选择类似于table.filter(...).length
  • 主要选择是table.map(...)
  • 然后看看我能不能让它们以某种方式结合起来。

【讨论】:

  • 谢谢!这让我到达了我需要的地方(请参阅更新的问题)。
猜你喜欢
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
相关资源
最近更新 更多