第二个内连接加倍计数结果

时间:2014-11-13 10:29:24

标签: mysql sql

我有表A,B和C.A有很多B和C.对于A我有6个B记录,其中一半被标记为已删除(deleted_at!= null)。

当我选择查询时

SELECT a.id, COUNT(b.id)
FROM table_a a 
INNER JOIN table_b b ON a.id = b.a_id AND b.deleted_at IS NULL
WHERE a.id = 5;

答案是正确的(id:5,count:3)

但是当我再添加一个内部联接时

SELECT a.id, COUNT(b.id)
FROM table_a a 
INNER JOIN table_b b ON a.id = b.a_id AND b.deleted_at IS NULL
INNER JOIN table_c c ON a.id = c.a_id AND c.deleted_at IS NULL
WHERE a.id = 5;

它加倍计数结果(id:5,count:6)

我该如何解决?

3 个答案:

答案 0 :(得分:1)

正如我们所提到的,你可以在这里计算不同的b ID。

但是,当需要来自各种表的聚合时,您的问题很常见。问题出现了,因为人们加入所有记录然后尝试获取聚合。

例如:

SELECT a.id, SUM(b.value)
FROM table_a a 
INNER JOIN table_b b ON a.id = b.a_id AND b.deleted_at IS NULL
INNER JOIN table_c c ON a.id = c.a_id AND c.deleted_at IS NULL
WHERE a.id = 5;

这与您的查询几乎相同。但是在这里你不能再使用DISTINCT了,因为如果你在b中有100,200,200的值,那么你将获得300而不是500。所以通用解决方案是:只加入实际加入的内容。以下是上述查询的两种解决方案:

解决方案1:加入前汇总:

SELECT a.id, b.total
FROM table_a a 
INNER JOIN 
(
   select a_id, sum(value) as total 
   from table_b 
   where deleted_at IS NULL
   group by a_id
) b ON a.id = b.a_id
INNER JOIN table_c c ON a.id = c.a_id AND c.deleted_at IS NULL
WHERE a.id = 5;

解决方案2:如果您只需要表中的一个值,请在SELECT子句中获取它:

SELECT a.id, 
(
   select sum(value)
   from table_b 
   where deleted_at IS NULL
   and a_id = a.id
)  as total 
FROM table_a a 
INNER JOIN table_c c ON a.id = c.a_id AND c.deleted_at IS NULL
WHERE a.id = 5;

答案 1 :(得分:0)

你可以计算不同的值

SELECT a.id, COUNT(DISTINCT b.id)
FROM table_a a 
INNER JOIN table_b b ON a.id = b.a_id AND b.deleted_at IS NULL
INNER JOIN table_c c ON a.id = c.a_id AND c.deleted_at IS NULL
WHERE a.id = 5;

答案 2 :(得分:0)

当我开始编程时,我遇到了同样的问题。 我不确切地知道你也面临同样的问题。

如果table_c与其他两个表有多个匹配的coulmns,即table_a&表-B 那么你需要在ON clause中添加另一个条件。

示例:

如果想的话 table_a由

组成
ID   |    Name  |   Secondary_id

table_b由

组成
ID   |    Some other coulmn |   

table_a由

组成
ID   |    Some coulmn  |   Secondary_id

然后在这种情况下,你的第三个表格table_c将有table_a

中的两个相同的coulmns

然后

现在你必须像这样编写查询。

select * from
table_a 
JOIN tablE_b ON  table_a.ID = table_b.ID
JOIN tablE_c ON  tablE_c.ID = table_b.ID and table_a.Secondary_id = table_b.Secondary_id 

请注意,我在ON clause

中添加了两个条件
ON  tablE_c.ID = table_b.ID and table_a.Secondary_id = table_b.Secondary_id 

我希望这会对你有所帮助