Rails和PostgreSQL在使用Having时出现问题

3

我正在尝试从以下Action表格中检索数据:

列: ID、Name、Status、Product_ID、User_ID等其他与此问题无关的列。

每当用户想要一个产品时,我就创建一个记录,如下所示: Name = Want,Status = True,Product_ID = 所需产品的ID,User_ID为用户的ID。

然后,每当用户不想要一个产品时,我就创建一个记录,如下所示: Name = Want,Status = False,Product_ID = 不需要的产品的ID,User_ID为用户的ID。

我之所以这样做是因为我的表中还有其他操作名称。

现在,我想检索所有想要的产品,因此应按降序排序特定用户的所有最新“want”操作(按product_id分组),然后仅检索状态为true的操作。

因此,为了获取按product_id分组的特定用户的所有最新“want”操作,我这样做:

Action.select("DISTINCT ON (product_id) product_id,created_at, status, * ").where{(user_id   == id) & (name == 'want')}.group("product_id, id, status").order(' product_id,created_at DESC')

检索每个产品和用户的最后操作,但同时检索真实和虚假状况。唯一的问题是我不知道如何过滤这个表格,只获取true状态的操作。

我尝试像这样做:


```javascript filter((item) => item.status === true) ```
Action.select("DISTINCT ON (product_id) product_id,created_at, status, * ").where{(user_id == id) & (name == 'want')}.group("product_id, id, status").having("status = 'true'").order(' product_id,created_at DESC')

但这将给我最后一个 want = true 的操作。如果最后一个行动是 status = false,它将检索在 status = true 时的上一个。

以下是我想要的一些想法,但我不知道如何在 Rails 中实现:http://sqlfiddle.com/#!9/e4117/3

1个回答

1
你可以尝试在条件中添加子查询并删除分组操作:
Action.
  where( user_id: id, name: "want", status: "true").
  where( ["id IN (SELECT max(id) FROM actions WHERE user_id = ?
              AND name = 'want' GROUP BY product_id)", id]).
  order( "product_id")

你需要依赖id列的顺序是最后一步操作才能正确地工作。如果你无法做到这一点,你可以在子查询中使用DISTINCT ON:
Action.
  where( user_id: id, name: "want", status: "true").
  where( ["id IN (SELECT DISTINCT ON (product_id) id FROM actions
              WHERE user_id = ? AND name = 'want'
              ORDER BY product_id, created_at DESC)", id]).
  order( "product_id")

如果我这样做,那将会给我所有的状态都是true,但是如果我有这个:最后一个项目是false状态,而倒数第二个项目是true状态,它将会给我倒数第二个项目。如果不是最后一个项目,我希望它返回空。谢谢。 - Jeremy B
谢谢,只有一个问题:ORDER BY product_id, created_at DESC)", user_id]). order( "product_id") 中的 user_id 应该改为 id 吗?谢谢。 - Jeremy B

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接