查询多个表的总和

时间:2013-04-03 13:18:28

标签: mysql sql spree

我在困难的查询中需要帮助。这与优惠券在Spree Commerce平台中实施的复杂方式有关。

我只需要优惠券总额。

表格是:

偏好

id | value  | key
---+---------------------------------------------
1  | 25     | spree/calculator/flat_rate/amount/5

计算器

id  | calculable_id | calculable_type
----+---------------+-----------------
5   | 3             | promotion_action

promotion_actions

id  | activator_id  
----+-------------
3   | 2

的活化剂

id | expires_at | usage_limit 
---+------------+------------
2  | 2013-12-01 | 4           

调整

originator_type  | originator_id | amount
-----------------+---------------+-------
promotion_action | 3             | -25

preferences.key中的最后一个数字对应于计算器的ID。

首先我需要prefers.amount的总数,乘以activators.usage_limit(除非activators.expires_at< today),其中preferences.key LIKE'%calculator / flat_rate%'。

结果应为此金额减去相应adjust.amount的总和

我到目前为止

select 
 (select sum(value) from spree_preferences 
   where `key` like "%calculator/flat_rate%") 
 + 
 (select sum(amount) from spree_adjustments 
   where originator_type = 'promotion_action') as total;

,但这并没有考虑到expires_at和usage_limit。

对于更新的狂欢,答案如下:

select sum(subAggregate.outstanding) from ( select (subDetail.value * subDetail.multiplier) + subDetail.adjustmentAmount as outstanding from ( select p.value, case when a.expires_at > curDate() then a.usage_limit else 1 end as multiplier , ifNull(adj.amount,0) as adjustmentAmount from spree_preferences p left outer join spree_calculators c on replace(p.key,'spree/calculator/flat_rate/amount/','') = c.id left outer join spree_promotion_actions pa on c.calculable_id = pa.id and c.calculable_type = 'Spree::PromotionAction' left outer join spree_promotions a on pa.promotion_id = a.id left outer join spree_adjustments adj on pa.id = adj.source_id and pa.type = 'Spree::PromotionAction' ) subDetail ) subAggregate

1 个答案:

答案 0 :(得分:2)

select sum(subAggregate.outstanding)
from
    (
    select (subDetail.value * subDetail.multiplier) + subDetail.adjustmentAmount as outstanding
    from
        (
        select  p.value,
                case
                    when a.expires_at > curDate() then a.usage_limit
                    else 1
                end as multiplier ,
                ifNull(adj.amount,0) as adjustmentAmount
        from    preferences p
                left outer join calculators c
                    on replace(p.key,'spree/calculator/flat_rate/amount/','') = c.id
                left outer join promotion_actions pa
                    on c.calculabel_id = pa.id
                    and c.calculable_type = 'promotion_action'
                left outer join activators a
                    on pa.activator_id = a.id
                left outer join adjustments adj
                    on pa.id = adj.originator_id
                    and pa.originator_type = 'promotion_action'
        ) subDetail
    ) subAggregate