查询内部查询,其中表2.amount(stat = 1)的总和大于表1费用的总和

时间:2013-10-26 09:17:33

标签: php mysql

我有两张桌子

表:的交易

id . user_id . amount . status
1 - - 100 -- --- 500 - ----- 1
2 - - 100 -- --- 100 - ----- 0
3 - - 110 -- --- 200 - ----- 1

表:广告系列

id . user_id . bid . status . budget . expense . size
1 -- 100 ---- 80  --- 1 ------- 200 ------ 200 ---- 5 --
2 -- 109 ---- 75  --- 1 ------- 050 ------ 030 ---- 2 --
3 -- 100 ---- 65  --- 1 ------- 700 ------ 065 ---- 2 --
4 -- 107 ---- 77  --- 0 ------- 020 ------ 020 ---- 2 --
5 -- 90 ----- 87  --- 1 ------- 120 ------ 090 ---- 7 --

在使用php和mysql

过滤后我需要campaign.id

条件:如果从用户收到的总金额/交易大于用户的总费用。资金也是经批准的资金(1 =已批准,0 =待定)。广告系列位于第1种方式,即最高出价

(sum(transaction.amount) WHERE transaction.status = 1 of that any user) > sum(campaign.expense of that user)

bid = max(bid)

营地状态= 1

1步解决方案

 mysql_query("SELECT campaign.* FROM campaign c,transaction t  
            WHERE budget>expense AND status='1' AND size='2' 
            ON c.user_id=t.user_id 
            HAVING SUM (CASE WHEN transaction.status=1 THEN transaction.amount ELSE 0 END) > SUM(campaign.expense)"));

无效

或者如果有3个步骤的任何解决方案 -

第一步

   mysql_query("SELECT id,user_id FROM campaign 
        WHERE budget>expense AND status='1' AND size='2'")

第二步

  keep id,user_id of 1st step WHERE SUM(transaction.amount status=1)
             > SUM(campaign.expense)

第3步

  mysql_query("SELECT id,user_id FROM campaign 
        WHERE step2 satisfied")

请帮忙,解决后我会睡觉

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT camps.id,camps.bid FROM camps c JOIN tran t  ON c.user_id=t.user_id 
    HAVING SUM (CASE WHEN tran.status=1 THEN tran.amount ELSE 0 END)
       > SUM(CASE WHEN camp.status= 1 THEN camps.expense ELSE 0 END)

答案 1 :(得分:0)

据我了解,您希望实现以下目标:

SELECT 
    c.*
FROM campaign c
JOIN (SELECT
        SUM(amount) AS summed
    FROM transaction t
    WHERE status = 1
) temp t
WHERE c.status = 1
HAVING t.summed > SUM(c.expense)
ORDER BY c.bid DESC
LIMIT 1