Php 添加多个表的字段时出现问题
我有三张结构相同的桌子 表1Php 添加多个表的字段时出现问题,php,mysql,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
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
现在我要的是表1,第一条记录“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
请帮忙。我该怎么办?您的问题是,首先,您使用的是
左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'
(小提琴是)。正如您所看到的,您将从第二个和第三个表中获得重复的id—是的,这是因为有多行用于连接条件
为了解决您的问题,您可以在join中添加按id区分的方法(稍后使用变量或类似的方法过滤),但我不推荐这样做<代码>加入根本不适合您的问题。使用联合
,如:
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
(请参阅)你是想做什么?谢谢@Jack它对我有用。。