-1

我有两张桌子

表:交易

id . user_id . amount . status
1 - - 100 -- --- 500 - ----- 1
2 - - 100 -- --- 100 - ----- 0
3 - - 110 -- --- 200 - ----- 1
4 - - 100 -- --- 220 - ----- 1
5 - - 117 -- --- 120 - ----- 1
6 - - 122 -- --- 300 - ----- 1

这意味着用户存款但只有status=1有效

表:活动

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

我需要以下过滤后的活动ID(使用php和mysql)

条件:

01. campaign.status = 1
02. campaign.size = 2
03. campaign.budget > campaign.expense

04. those user_id has balance (balance = A - B)
      A = sum(transaction.amount where transaction.status=1)
      B = sum(campaign.expense)
05. order by bid max value

预期输出campaign.id = 3

for campaign.id 3 :  status 1, size 2, budget 700 > expense 65
balance > 0 means for user_id 100 = A(500+220) > B(200+65) //means A-B = 455

我不是那么专家。尝试了几种方法

请帮忙,解决后我会睡觉的。输了2天。

4

1 回答 1

0

一种可能的解决方案:

SELECT *
FROM campaign c
WHERE 
  c.status = 1
  AND c.size = 2
  AND c.budget > c.expense
  AND
    ( SELECT sum( amount )
      FROM transaction t
      WHERE t.user_id = c.user_id
    )
   -
    ( SELECT sum( expense )
      FROM campaign c1
      WHERE c.user_id = c1.user_id AND t.status=1
    )
    > 0
;

另一个:

SELECT c.*
FROM (
   SELECT user_id, sum( amount ) amount
   FROM transaction t
   WHERE EXISTS(
      SELECT 1 FROM campaign c
      WHERE t.user_id = c.user_id
        AND c.status = 1 
        AND c.size = 2
        AND c.budget > c.expense
     )
   GROUP BY user_id
) q1
JOIN (
   SELECT user_id, sum( expense ) expense
   FROM campaign c
   WHERE EXISTS(
      SELECT 1 FROM campaign c1
      WHERE c.user_id = c1.user_id
        AND c1.status = 1 
        AND c1.size = 2
        AND c1.budget > c.expense
     )
   GROUP BY user_id
) q2
ON q1.user_id = q2.user_id AND q1.amount - q2.expense > 0
JOIN campaign c
ON c.user_id = q1.user_id
WHERE c.status = 1 
  AND c.size = 2
  AND c.budget > c.expense

演示(两个查询):http

://www.sqlfiddle.com/#!2/414ca5/ 2 请在您的数据上尝试这两个,我不确定哪个会表现更好(可能是第一个)。

两个查询至少需要user_id两个表的列索引以获得更好的性能:

CREATE INDEX camp_user_id ON campaign( user_id );
CREATE INDEX trans_user_id ON transaction( user_id );
于 2013-10-26T17:45:46.710 回答