为什么我在四个表之间的连接中得到重复项?
Why am I getting duplicates in a join between four tables?
表和查询在这里
http://sqlfiddle.com/#!9/2b6f35a/1/0
在每个名字中我都得到它的标签标题,所以它会像这样
name1: title1;
name2: title1;
name3: title1;
我的问题是我得到了双倍的标签
name1: title1, title1;
name2: title1, title1;
name3: title1;
我犯了什么错误?
整个问题都来自tablx
抱歉之前乱七八糟的,不知道sqlfiddle
如果发布的问题中的所有内容都是正确的,那么您就没有做错任何事情。
查看这个 sqlfiddle:
与 X table 的连接返回第 4 行。 http://sqlfiddle.com/#!9/2b6f35a/6,它从标签 table 中提取相同的 title1
值,然后用 GROUP_CONCAT()
聚合到最终响应中
如果您需要在一个查询中加入这两个 table 但只需要 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 的费率列上使用聚合器可能更有用,如下所示: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
表和查询在这里
http://sqlfiddle.com/#!9/2b6f35a/1/0
在每个名字中我都得到它的标签标题,所以它会像这样
name1: title1;
name2: title1;
name3: title1;
我的问题是我得到了双倍的标签
name1: title1, title1;
name2: title1, title1;
name3: title1;
我犯了什么错误?
整个问题都来自tablx
抱歉之前乱七八糟的,不知道sqlfiddle
如果发布的问题中的所有内容都是正确的,那么您就没有做错任何事情。
查看这个 sqlfiddle:
与 X table 的连接返回第 4 行。 http://sqlfiddle.com/#!9/2b6f35a/6,它从标签 table 中提取相同的 title1
值,然后用 GROUP_CONCAT()
如果您需要在一个查询中加入这两个 table 但只需要 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 的费率列上使用聚合器可能更有用,如下所示: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