gpt4 book ai didi

mysql - 在派生表上使用复杂联接的 Active Record 查询?

转载 作者:行者123 更新时间:2023-11-30 00:53:01 25 4
gpt4 key购买 nike

我正在使用 Ruby、Sinatra 和 MySQL。我有四张 table 。

联系人(客户):

class Contact < ActiveRecord::Base
attr_accessible :id, :company_id, :name, :address, ...

has_many :orders, :dependent => :destroy
has_many :ordered_products
...
end

订单:

class Order < ActiveRecord::Base
attr_accessible :id, :name, :contact_id, ...

belongs_to :contact

has_many :ordered_products, :dependent => :destroy
has_many :products, :through => :ordered_products
...
end

订购产品:

class OrderedProduct < ActiveRecord::Base
attr_accessible :quantity, :price, :contact_id, :product_id, :order_id ...

belongs_to :contact
belongs_to :product
belongs_to :order
...
end

和产品:

class Product < ActiveRecord::Base
attr_accessible :id, :name, :producer, :region, :size ...

has_many :ordered_products, :dependent => :destroy
has_many :orders, :through => :ordered_products
...
end

我编写了以下 SQL 查询来获取以联系人为中心的统计信息。

SELECT `contacts`.`name`,
MIN(orderTotals) AS min,
AVG(orderTotals) AS avg,
MAX(orderTotals) AS max,
SUM(`ordered_products`.`price` * `ordered_products`.`quantity`) AS total,
CAST(COUNT(DISTINCT `orders`.`id`) AS UNSIGNED) AS ordersNumber,
CAST(SUM(`ordered_products`.`quantity`) AS UNSIGNED) AS productsNumber
FROM `contacts`
INNER JOIN `orders` ON `orders`.`contact_id` = `contacts`.`id`
INNER JOIN `ordered_products` ON `ordered_products`.`order_id` = `orders`.`id`
INNER JOIN `products` ON `products`.`id` = `ordered_products`.`product_id`
INNER JOIN
(
SELECT contact_id as identifier,
SUM(`ordered_products`.`price` * `ordered_products`.`quantity`) as orderTotals
FROM `ordered_products`
GROUP BY `ordered_products`.`order_id`
) `sumTable`
ON `sumTable`.`identifier` = `contacts`.`id`
WHERE `contacts`.`company_id` = 74
AND (`orders`.`updated_at` >= '2013-01-01 00:01:59')
AND (`orders`.`updated_at` <= '2013-12-31 23:59:59')
AND (`orders`.`order_state_id` = '100')
GROUP BY `contacts`.`id`
ORDER BY `contacts`.`name` ASC
LIMIT 20
OFFSET 0;

我想将其完全转换为 Active Record 格式。我能够正确地转换并运行它,但是下面的内部连接让我困惑,我不得不直接粘贴 SQL:

.joins('INNER JOIN (SELECT contact_id as identifier,
SUM(ordered_products.price * ordered_products.quantity) as orderTotals
FROM `ordered_products` GROUP BY ordered_products.order_id) `sumTable`
ON `sumTable`.`identifier` = `contacts`.`id`').

我只报告翻译后的 SQL 查询的一个片段,因为派生表上联接的翻译对我来说最重要。我发现它远没有那么优雅和可读,例如:

Contact.joins(orders: [{ordered_products: :product}]). ...

如有任何帮助,我们将不胜感激!

谢谢,卢卡

最佳答案

无法完全告诉你要做什么,因为其余代码不存在,但如果你使用 Postgres,你可能需要查看 pg_search gem,因为它可能会为你节省一些 SQL 工作看起来更新/维护可能会很痛苦。

关于mysql - 在派生表上使用复杂联接的 Active Record 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20808908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com