是否有 Ruby/Rails 子句用于按属性分组并查找具有两个不同属性的组?
Is there a Ruby/Rails clause for grouping by an attribute and finding groups with two different attributes?
我有很多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"]
]
您可以在 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";
这将 return 只是相关的 user_ids。
有了这些数据,您可以使分组查询变得更加简单:
user_ids = Sandwich.connection.execute(the_above_sql).flatten
Sandwich.where(user_id: user_ids).group(:user_id)
我有很多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"]
]
您可以在 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";
这将 return 只是相关的 user_ids。
有了这些数据,您可以使分组查询变得更加简单:
user_ids = Sandwich.connection.execute(the_above_sql).flatten
Sandwich.where(user_id: user_ids).group(:user_id)