Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 匹配每个子集元素的活动记录查询_Sql_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

Sql 匹配每个子集元素的活动记录查询

Sql 匹配每个子集元素的活动记录查询,sql,ruby-on-rails,ruby,activerecord,Sql,Ruby On Rails,Ruby,Activerecord,在我的RoR应用程序中,我有一个与此类似的数据库查找: 不幸的是,这将返回所有购买了产品1、2或3的客户,但我只想返回购买了这三种产品的所有客户。换句话说,我想写一个查询,匹配给定集合中的n个元素 有什么优雅的解决方案吗?这不是很优雅。但它应该转换成所需的SQL Client.joins(:products). where({'products.id' => [1,2,3]}). group('users.id'). having('COUNT(

在我的RoR应用程序中,我有一个与此类似的数据库查找:

不幸的是,这将返回所有购买了产品1、2或3的客户,但我只想返回购买了这三种产品的所有客户。换句话说,我想写一个查询,匹配给定集合中的n个元素


有什么优雅的解决方案吗?

这不是很优雅。但它应该转换成所需的SQL

Client.joins(:products).
       where({'products.id' => [1,2,3]}).
       group('users.id').
       having('COUNT(DISTINCT products.id) >= 3')

同样的答案更具活力

ids = [1,2,3]

Client.joins(:products).
       where({'products.id' => ids}).
       group('users.id').
       having('COUNT(DISTINCT products.id) >= ?', ids.size)

如果同样的产品买了3次会怎么样?@emaillenin:
DISTINCT
应该可以处理。漂亮的解决方案+1(我本来打算做一个
GROUP\u CONCAT
让我的GROUP\u排序=='1 2 3'
,但你的解决方案非常出色:-)
ids = [1,2,3]

Client.joins(:products).
       where({'products.id' => ids}).
       group('users.id').
       having('COUNT(DISTINCT products.id) >= ?', ids.size)