我有两张桌子可以高效地将数据拉出来。
TableA
id
full_name
TableB
table_a_id_1
table_a_id_2
amount1
amount2
TableB引用TableA上的两个不同记录(它们将永远不会相同)
我正在尝试编写1个查询(或最有效的查询,试图避免n + 2查询)以获取TableA中所有记录的列表以及相应TableB的总计和
它看起来像这样:
[{id: 1, full_name: 'bob', 1_sum1: 50.0, 1_sum2: 30.0, 2_sum1: 1.0, 2_sum2: 25.0}]
,其中 id和full_name来自TableA
1_sum1,1_sum2,是TableB中的总和列,其中table_a_id_1 = TableA.id
2_sum1,2_sum2都是TableB中的总和列,其中table_a_id_2 = TableA.id
我真的希望这不会令人困惑。我有这样的查询:
results = TableA.
joins('LEFT JOIN table_b t1_stats ON t1_stats.t1_aff_id = table_a.id').
joins('LEFT JOIN table_b t2_stats ON t2_stats.t2_aff_id = table_a.id').
select("table_a.*,
sum(t1_stats.amount1) AS 1_sum1,
sum(t2_stats.amount1) AS 2_sum1,
sum(t1_stats.amount2) AS 1_sum2,
sum(t2_stats.amount2) AS 2_sum2").
group('table_a.id')
我没有得到总和的结果是正确的。我认为它是因为它应该只是在table_b的记录中对1_sum1的记录求和,其中table_a_id_1 = table_a.id,而我认为它可能包括所有记录,然后对它们求和。
我是否需要进行子选择或其他操作?这不是我的强项,所以任何帮助解决这个问题都会很棒!
由于
答案 0 :(得分:0)
尝试:
results = TableA.
select("table_a.*,
(SELECT sum(table_b.amount1) FROM table_b WHERE table_b.t1_aff_id = table_a.id) AS 1_sum1,
(SELECT sum(table_b.amount2) FROM table_b WHERE table_b.t1_aff_id = table_a.id) AS 1_sum2,
(SELECT sum(table_b.amount1) FROM table_b WHERE table_b.t2_aff_id = table_a.id) AS 2_sum1,
(SELECT sum(table_b.amount2) FROM table_b WHERE table_b.t2_aff_id = table_a.id) AS 2_sum2")