我有一个客户端模型和一个产品模型,其中一个客户端有多个产品,一个产品属于一个CLient。
我需要查找一个查询,该查询仅返回在Product表中有记录的客户端
客户端表
id | name
--------------
1 | Company A
2 | Company B
3 | Company Cproducts表
id | name | client_id
---------------------------
1 | Product A | 1
2 | Product B | 1
3 | Product C | 3
4 | Product D | 3
5 | Product E | 1我只需要客户1 3
例如,类似于
@clients = Client.where("client exists in products") #something to this effect发布于 2013-01-07 14:13:55
最简单但不是最快的:
Client.where(:id => Product.select(:client_id).map(&:client_id))SQL子查询(更快):
Client.where("EXISTS(SELECT 1 from products where clients.id = products.client_id)")发布于 2015-07-29 02:34:20
这里有另一个解决方案。它是一个子查询,类似于Valery的第二个解决方案,但没有写出sql:
Client.where(Product.where(client_id: Client.arel_table[:id]).exists)发布于 2015-08-31 02:53:59
以下是使用Where Exists gem的解决方案(披露:我是它的作者):
Client.where_exists(:products)https://stackoverflow.com/questions/14188872
复制相似问题