简体   繁体   English

连接多个表时,Rails / MySQL查询获取计数

[英]Rails/MySQL query to get the count when joining multiple tables

I have a rails app with the following structure: A Dealer can have many Cars, which in turn can have many different Promotions on it (car_promotions is a table linking the promotion to the car itself). 我有一个具有以下结构的Rails应用程序:经销商可以拥有许多汽车,而汽车上又可以具有许多不同的促销(car_promotions是将促销链接到汽车本身的表)。

What I am trying to do is for each dealer, get a count of the number of each different car_promotion they currently have. 我要为每个经销商做的事情是,计算出他们当前拥有的每种不同的car_promotion的数量。 So for example, if there is a promotion called "5% off" and one called "free shipping", it would fine the number of cars that have the first promotion, and the number of cars that have the second promotion. 因此,例如,如果有一个名为“ 5%off”的促销活动和一个名为“免费送货”的促销活动,它将对具有第一次促销活动的汽车数量和具有第二次促销活动的汽车数量进行罚款。

Dealer.rb: Dealer.rb:

has_many :cars, :promotions

Car.rb: Car.rb:

has_many :car_promotions
attr_accessor :dealer_id

CarPromotion.rb: CarPromotion.rb:

belongs_to :car, :promotion.rb
attr_accessor :car_id, :promotion_id

Promotion.rb Promotion.rb

belongs_to :dealer

Currently what I am doing is doing joining the cars and car_promotions models, and then for each promotion the dealer has in their database, cycle through them and getting the number of rows in my join which refers to the promotion. 目前,我正在做的工作是加入cars和car_promotions模型,然后针对经销商在其数据库中的每个促销活动,循环浏览它们,并获取我的联接中涉及促销的行数。 This is working, but its really slow, so I am wondering how I can optimize it (using either rails queries, or mysql queries). 这是可行的,但是它确实很慢,所以我想知道如何优化它(使用rails查询或mysql查询)。 My sql query writing isn't great, so I am having some issues getting it to work correctly. 我的sql查询编写不是很好,所以我在使其正常工作方面遇到一些问题。

I also tried using a group_by on my joins, but I wasn't sure how to get that working, since if I just do a group_by directly on the joins, it doesn't have a reference to the promotion_id. 我也尝试在联接上使用group_by,但是我不确定如何使它工作,因为如果我直接在联接上直接执行group_by,则它没有对promotion_id的引用。

Any ideas? 有任何想法吗? Thanks, 谢谢,

Once you go beyond two tables, I find often find it easier to write raw SQL. 一旦您超出了两个表,我发现通常会发现编写原始SQL更容易。 This might do what you want: 这可能会满足您的要求:

SELECT COUNT(cp.id), d.id
FROM car_promotians cp
  INNER JOIN cars c ON cp.car_id = c.id
  INNER JOIN dealers d ON c.dealer_id = d.id
GROUP BY d.id

Getting an efficient SQL query via ActiveRecord is probably possible. 通过ActiveRecord获得有效的SQL查询是可能的。 If you post your database schema, it might be easier for someone to help you. 如果您发布数据库架构,则有人可以更轻松地为您提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM