0

我有以下 SQL:

SELECT
          t.amount
        FROM
          transactions t
        JOIN contracts c ON t.contractId = c.id
        JOIN insertions i ON c.id = i.contractId
        JOIN magazines m ON i.magazineId = m.id
        WHERE m.id = 26
          AND t.isChargedBack IS FALSE
          AND t.`timestamp` >= '2013-09-12'
          AND t.`timestamp` <= date_add('2013-09-12',interval 1 month)
        GROUP BY 
          t.id;

产生:

1100
800
1025
500
1200
552
395
395
1170
1000
675

我只想要这个结果的总和。我预计8812。

所以我使用以下 SQL:

SELECT
          IFNULL(SUM(t.amount),0)
        FROM
          transactions t
        JOIN contracts c ON t.contractId = c.id
        JOIN insertions i ON c.id = i.contractId
        JOIN magazines m ON i.magazineId = m.id
        WHERE m.id = 26
          AND t.isChargedBack IS FALSE
          AND t.`timestamp` >= '2013-09-12'
          AND t.`timestamp` <= date_add('2013-09-12',interval 1 month)
        GROUP BY 
          t.id;

这是我的结果:

39600
9600
61500
9000
43200
49680
14220
5925
7020
36000
72900

???

4

1 回答 1

1

您的原始查询有问题。它没有做你认为它正在做的事情。您正在汇总t.id,但选择t.amount。这意味着 MySQL 正在选择一个任意值。

为什么会这样?一种可能性是以下每​​笔交易的正确金额:

    SELECT sum(t.amount)
    FROM transactions t
    JOIN contracts c ON t.contractId = c.id
    JOIN insertions i ON c.id = i.contractId
    JOIN magazines m ON i.magazineId = m.id
    WHERE m.id = 26
      AND t.isChargedBack IS FALSE
      AND t.`timestamp` >= '2013-09-12'
      AND t.`timestamp` <= date_add('2013-09-12',interval 1 month)
    GROUP BY t.id;

如果是这样,只需删除group by将给出正确的总数。

另一种可能性是joins 正在乘以行。我的怀疑是insertions。如果是这种情况,那么t.amount将被重复,并且您想要的查询将只选择一个值:

    SELECT min(t.amount)
    FROM transactions t
    JOIN contracts c ON t.contractId = c.id
    JOIN insertions i ON c.id = i.contractId
    JOIN magazines m ON i.magazineId = m.id
    WHERE m.id = 26
      AND t.isChargedBack IS FALSE
      AND t.`timestamp` >= '2013-09-12'
      AND t.`timestamp` <= date_add('2013-09-12',interval 1 month)
    GROUP BY t.id;

如果这是问题所在,那么要获得完整的总和,您可以使用子查询:

select sum(amount)
from (SELECT min(t.amount) as amount
      FROM transactions t
      JOIN contracts c ON t.contractId = c.id
      JOIN insertions i ON c.id = i.contractId
      JOIN magazines m ON i.magazineId = m.id
      WHERE m.id = 26
        AND t.isChargedBack IS FALSE
        AND t.`timestamp` >= '2013-09-12'
        AND t.`timestamp` <= date_add('2013-09-12',interval 1 month)
      GROUP BY t.id
     ) t
于 2013-09-18T19:28:49.393 回答