简体   繁体   English

到多个MySQL关系中的许多记录(与添加关系的关系)-GROUP BY与JOIN?

[英]To much records in multiple MySQL relation (relation with adding relation) - GROUP BY with JOIN?

i have 3 tables: 我有3张桌子:

# table1 #
## id ##
   1

# table2 #
## id    table1 ##
   1       1
   2       1
   3       1

# table3 #
## id    table2 ##
   1       1
   2       1
   3       2
   4       2
   5       3
   6       3

And query, who join 3 tables in single query 和查询,谁在单个查询中联接3个表

Select COUNT(t2.id)
FROM table1 t1
LEFT OUTER JOIN table2 t2 ON t2.table1 = t1.id
LEFT OUTER JOIN table3 t3 ON t3.table2 = t2.id
WHERE t1.id = 1
GROUP BY t1.id

COUNT(t2.id) should return 3, but i get 6 - I think that is because every record from table2 have 2 records in table3. COUNT(t2.id)应该返回3,但我得到6-我认为这是因为table2中的每个记录在table3中都有2条记录。

Maybe I should change this line? 也许我应该改变这条线?

LEFT OUTER JOIN table3 t3 ON t3.t2 = t2.id

Maybe group this or something? 也许将其分组? But how do this? 但是怎么办呢?

====================================== edit ====================================编辑

add to table2 column "price" 添加到table2列“价格”

# table2 #
## id    table1    price ##
   1       1        10
   2       1        20
   3       1        10

Select SUM(t2.price)
FROM table1 t1
LEFT OUTER JOIN table2 t2 ON t2.table1 = t1.id
LEFT OUTER JOIN table3 t3 ON t3.table2 = t2.id
WHERE t1.id = 1
GROUP BY t1.id

Now, when I want to sum the price I get 80, but I should get 40 - distinct is not good solution, because price is not unique. 现在,当我想对价格求和时,我得到80,但我应该得到40-由于价格不是唯一的,与众不同并不是一个好的解决方案。

Change 更改

Select COUNT(t2.id)

to

Select COUNT(distinct t2.id)

and remove the group by since you select only one group anyway with WHERE t1.id = 1 并删除group by因为无论如何您只选择了一个WHERE t1.id = 1

You said: If this is not exactly that what I need. 您说:如果这不是我所需要的。 Suppose - in table2 I have another column "price" and in my query I trying to get this: SUM(t2.price) - then I get double sum - reason as above. 假设-在表2中,我还有另一列“价格”,而在我的查询中我试图得到此值:SUM(t2.price)-然后我得到了两倍的总和-原因如上所述。 Distinct is not good idea, becouse this column don't have unique value. 区分不是一个好主意,因为此列没有唯一的价值。 How I can resolve this? 我该如何解决?

Remove the join to table3: 删除对table3的联接:

Select COUNT(t2.id)
FROM table1 t1
  LEFT JOIN table2 t2 ON t2.table1 = t1.id
WHERE t1.id = 1;

When you are joining against t3 you are expanding the rows to 6. 当您针对t3加入时,您会将行扩展到6。

Select sum(t2.price)
FROM table1 t1
LEFT OUTER JOIN table2 t2 ON t2.table1 = t1.id
WHERE t1.id = 1;

Please check SQL Fiddle http://sqlfiddle.com/#!2/2236fb/11 请检查SQL Fiddle http://sqlfiddle.com/#!2/2236fb/11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM