具有多个条件的另一个表中的数据

时间:2013-10-26 15:33:40

标签: php mysql join

我有两张桌子

表:的交易

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

这意味着用户存款,但只有状态= 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天。

1 个答案:

答案 0 :(得分: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 );