首页 > 解决方案 > 是否有用于按属性分组并查找具有两个不同属性的组的 Ruby/Rails 子句?

问题描述

我有Sandwich很多

我希望将它们分组:user_id

user_id组至少有一个三明治jelly和一个peanut butter

我最好的尝试是:

Sandwich.group(:user_id).having('topping = ? AND topping = ?', "jelly", "peanut butter")

但我认为语法更适合计数。

这些将是我想要的比赛..

[
  [user_id: "X123", topping: "peanut_butter"],
  [user_id: "X123", topping: "jelly"]
],
[
  [user_id: "Y444", topping: "peanut_butter"],
  [user_id: "Y444", topping: "jelly"],
  [user_id: "Y444", topping: "jelly"]
]

标签: ruby-on-railsrubygroupingarel

解决方案


您可以使用内部联接在 SQL 中实现此目的:

SELECT DISTINCT sandwiches.user_id
FROM sandwiches
INNER JOIN sandwiches sandwiches_alias
  ON sandwiches.user_id = sandwiches_alias.user_id
WHERE sandwiches.topping = "jelly"
  AND sandwiches_alias.topping = "peanut butter";

这将只返回相关的 user_ids。

使用这些数据,您可以使分组查询更加简单:

user_ids = Sandwich.connection.execute(the_above_sql).flatten
Sandwich.where(user_id: user_ids).group(:user_id)

推荐阅读