如何为这种情况编写SQL语句?

时间:2016-03-27 06:44:50

标签: php mysql

我有3张表格如下:

  • tbl_campaign_name
  • tbl_backer
  • payment_cellcard

我想从tbl_campaign_name中选择所有广告系列名称,但需要tbl_backerpayment_cellcard的组合。

组合应该如何?

嗯,tbl_backer中有字段作为金额,但它也有一个状态字段,我认为1为已批准,0为未批准。 payment_cellcard没有状态,这意味着它始终被批准。

问题:

我想从tbl_campaign_name中选择广告系列名称,将其列在一个列表中,其中包含已从tbl_backer批准的金额,并与始终获得批准的payment_cellcard相加。

下面是我的查询,即使tbl_backer的状态尚未获得批准,它总结了金额。

SELECT
    tbl_campaign_name.camp_id                      AS camp_id,
    tbl_campaign_name.is_featured                  AS is_featured,

    SUM(ifnull(payment_cellcard.payment_cellcard_amount, 0)) 
                                                   AS cellcard,
    SUM( ifnull(tbl_backer.total_amount, 0)) 
                                                   AS backed_amount,
    (SUM( ifnull(payment_cellcard.payment_cellcard_amount, 0)) +
            SUM( ifnull(tbl_backer.total_amount, 0))) 
                                                   AS total_donation
FROM ((tbl_campaign_name
LEFT JOIN tbl_backer
    ON ((tbl_campaign_name.camp_id = tbl_backer.camp_id)))
LEFT JOIN payment_cellcard
    ON ((tbl_campaign_name.camp_id = payment_cellcard.camp_id)))
WHERE (tbl_campaign_name.is_featured = 1)
GROUP BY tbl_campaign_name.camp_id
ORDER BY (SUM( ifnull(payment_cellcard.payment_cellcard_amount, 0)) + SUM(ifnull(tos_backer.total_amount, 0))) DESC, 
        tbl_campaign_name.camp_id

结果: 我按照自己的意愿列出了所有项目,但它总结了

tbl_backer.backer_status = 0

我希望这清楚地解释了我想要的东西。

谢谢,

0 个答案:

没有答案