添加多个表的字段的问题

时间:2014-07-15 07:03:34

标签: php mysql

我有三张相同结构的表。

表1

id  | email         | count    
1   | test1@abc.com | 5    
2   | test2@abc.com | 5
3   | test3@abc.com | 5

表2

id  | email         | count    
1   | test1@abc.com | 50    
2   | test1@abc.com | 50    
3   | test3@abc.com | 50

表3

id  | email         | count    
1   | test1@abc.com | 40    
2   | test1@abc.com | 45    
3   | test1@abc.com | 50

现在我想要的是table1,第一个记录" test1@abc.com" ;,我需要总和" count"下两个表的字段。所以我用下面的查询

SELECT (IFNULL(sum(distinct(table2.count)), 0) +     
IFNULL(sum(distinct(table3.count)), 0)) as total 
FROM table1 
LEFT JOIN table2 ON table1.email = table2.email 
LEFT JOIN table3 ON table1.email = table3.email 
WHERE table1.email = 'test1@abc.com'

此查询给出了以下记录:

185

但结果如下:

235

这是因为我在添加字段时使用了distinct。但如果我不使用distinct,它会给我285

请帮忙。我该怎么办?

1 个答案:

答案 0 :(得分:2)

您的问题是因为,首先,您使用LEFT JOIN(由于空记录不会提供任何内容,因此无意义求和),其次是JOIN的工作方式。用查询说明:

SELECT
  t1.id AS id_1,
  t1.email AS email_1,
  t1.count AS count_1,
  t2.id AS id_2,
  t2.email AS email_2,
  t2.count AS count_2,
  t3.id AS id_3,
  t3.email AS email_3,
  t3.count AS count_3
FROM
  table1 AS t1
    INNER JOIN table2 AS t2 ON t1.email=t2.email
    INNER JOIN table3 AS t3 ON t1.email=t3.email
WHERE
  t1.email='test1@abc.com'

(小提琴是here)。正如您所看到的,您将从第二个和第三个表中获得重复的ID - 并且 - 是的,因为有多行用于连接条件。

要解决您的问题,您可以通过id添加区别到连接(以及稍后使用变量或类似的过滤),但我不推荐它。 JOIN根本不适合您的问题。使用UNION,例如:

SELECT 
  SUM(`count`) AS s
FROM
  (
    SELECT
      table2.count
    FROM
      table2
    WHERE
      email='test1@abc.com'
    UNION ALL
    SELECT
      table3.count
    FROM
      table3
    WHERE
      email='test1@abc.com'
  ) AS u

(参见fiddle