MySQL - 跨表

时间:2016-05-12 08:35:01

标签: mysql count

我正在尝试跨多个链接表执行计数:

select 
    vpp.Name
    ,count(sx.Occurences) as sx_Occurences
    ,count(vpp.Occurences) as vpp_Occurences
    ,count(sd.Occurences) as sd_Occurences
from v_p vpp
  left outer join s_x sx on sx.ID = vpp.ID
  left outer join s_d sd on sd.ID = vpp.ID 
  group by vpp.Name

然而,这给了我不正确的结果(对一个表进行计数只能正常工作,但只要我添加第二个(或第三个,第四个......),数字就错了。

2 个答案:

答案 0 :(得分:0)

我相信你正在寻找这个:

SELECT vpp.Name,
       (SELECT count(sx.Occurences) FROM s_x WHERE s_x.ID = vpp.ID) as sx_Occurences, 
       count(vpp.Occurences) as vpp_Occurences,
       (SELECT count(sd.Occurences) FROM s_d WHERE s_d.ID = vpp.ID) as sd_Occurences
  FROM v_p vpp
 GROUP BY vpp.Name;

答案 1 :(得分:0)

您可能在3个表中至少有2个之间存在1:n的关系。在结果集中,如果您按单独计算每个表的记录,则会有比记录更多的记录。

如果要计算给定字段的不同值,请使用count(distinct ...):

select 
    vpp.Name
    ,count(distinct sx.Occurences) as sx_Occurences
    ,count(distinct vpp.Occurences) as vpp_Occurences
    ,count(distinct sd.Occurences) as sd_Occurences
from v_p vpp
  left outer join s_x sx on sx.ID = vpp.ID
  left outer join s_d sd on sd.ID = vpp.ID 
  group by vpp.Name

否则,您需要按每个表单独进行计数。您可以将3个查询组合为子查询:

select 
    t1.Name
    ,sx_Occurences
    ,vpp_Occurences
    ,sd_Occurences
from 
  (select name, id, count(vpp.Occurences) as vpp_Occurences
   from v_p vpp
   group by name, id) t1
  left outer join 
  (select id, count(sx.Occurences) as sx_Occurences
   from s_x sx
   group by id) t2 on t1.ID = t2.ID
  left outer join
  (select id, count(sd.Occurences) as sd_Occurences
   from s_d sd
   group by id) t3 on t1.ID = t3.ID