为什么我在四个表之间的连接中得到重复项?

时间:2017-10-16 19:44:09

标签: mysql sql cartesian-product

表和查询在这里

http://sqlfiddle.com/#!9/2b6f35a/1/0

在每个名字中我得到它的标签标题,所以就像这样

name1: title1;
name2: title1;
name3: title1;

我的问题是我得到了双倍的标签

name1: title1, title1;
name2: title1, title1;
name3: title1;

我犯的错误是什么?

整个问题出现在tablx

对于之前的烂摊子感到抱歉,不知道有关sqlfiddle的信息

2 个答案:

答案 0 :(得分:1)

与X表的连接返回第4行。 http://sqlfiddle.com/#!9/2b6f35a/6,从标记表中绘制相同的title1值,然后使用GROUP_CONCAT()

汇总到最终回复中

如果您需要在一个查询中同时加入这两个表,但只想要title1一次,则需要删除GROUP_CONCAT()聚合器:http://sqlfiddle.com/#!9/2b6f35a/7


    SELECT a.name, x.rate, c.title
    FROM tabl1 a 
    LEFT JOIN tablx x ON x.pid = a.id 
    INNER JOIN tabl2 b ON a.id = b.pid 
    INNER JOIN tabl3 c ON c.id = b.bid 
    WHERE c.title IN ('title1') 
    GROUP BY a.id

在您的情况下,在x table的rate列上设置聚合器可能更有用,例如:http://sqlfiddle.com/#!9/2b6f35a/9


    SELECT a.name, x.rate, c.title, SUM(x.rate) AS rate_sum
    FROM tabl1 a 
    LEFT JOIN tablx x ON x.pid = a.id 
    INNER JOIN tabl2 b ON a.id = b.pid 
    INNER JOIN tabl3 c ON c.id = b.bid 
    WHERE c.title IN ('title1') 
    GROUP BY a.id

如果您只想在此情况下计算不同标记的数量,则可以使用COUNT(DISTINCT...)http://sqlfiddle.com/#!9/2b6f35a/15

    SELECT a.name, b.id as bid, c.title, x.id as xid, x.rate, c.title, SUM(x.rate) AS rate_sum, COUNT(DISTINCT c.title) as title_count
    FROM tabl1 a 
    LEFT JOIN tablx x ON x.pid = a.id 
    INNER JOIN tabl2 b ON a.id = b.pid 
    INNER JOIN tabl3 c ON c.id = b.bid 
    WHERE c.title IN ('title1') 
    GROUP BY a.id

答案 1 :(得分:0)

如果发布的问题中的所有内容都是正确的,那么您没有做错任何事。

请参阅此sqlfiddle:

http://sqlfiddle.com/#!9/03205d/1