防止JOIN一遍又一遍地匹配同一行

时间:2014-04-17 14:41:13

标签: mysql sql

所以我有2张这样的表

trans_data table

mnth| id | units
2   | ab | 20
3   | cd | 20
2   | ab | 25
2   | fd | 28
2   | ab | 40
2   | cd | 70
3   | ab | 80
2   | ab | 10

配额表

mnth | metric | id | quota
2    | 1      | ab | 30
2    | 1      | cd | 30
2    | 1      | fd | 30
3    | 1      | ab | 40
3    | 1      | cd | 40
3    | 1      | fd | 40

这是我的SQL

SELECT 
  SUM(trans_data.units) AS ga, SUM(quota.quota)
FROM
  trans_data 
  LEFT JOIN quota ON 
  trans_data.id = quota.id
  AND quota.mnth BETWEEN 2 AND 2 
  AND quota.metric = 1
WHERE trans_data.id = 'ab'    
  AND trans_data.mnth BETWEEN 2 AND 2

正在发生的事情是,由于trans_data表中有多行有id='ab',因此这些行中的每一行都与配额中具有id='ab'的一行配对

这会抛出总和值。我该怎么办才能在sum()计算

中重复配额行

所需结果:

sum(trans_data.units)   |  sum(Quota.quota)
183                     | 30

2 个答案:

答案 0 :(得分:2)

您不需要INNER JOIN,只需单独计算两个总和:

SELECT ga, total_quota
FROM (SELECT SUM(units) AS ga
      FROM trans_data
      WHERE id = 'ab'
      AND mnth BETWEEN 2 AND 2) AS t1
CROSS JOIN
     (SELECT SUM(quota) AS total_quota
      FROM quota
      WHERE id = 'ab'
      AND mnth BETWEEN 2 AND 2
      AND metric = 1) AS t2

或者:

SELECT
     (SELECT SUM(units)
      FROM trans_data
      WHERE id = 'ab'
      AND mnth BETWEEN 2 AND 2) AS ga,
     (SELECT SUM(quota)
      FROM quota
      WHERE id = 'ab'
      AND mnth BETWEEN 2 AND 2
      AND metric = 1) AS total_quota

答案 1 :(得分:0)

在这种情况下,您实际上不需要对配额求和,因为只有一个单行。在这种情况下,您可以将sum函数更改为max函数。一般来说,Barmar的解决方案是最好的,因为它会处理多行,如果发生的话。