MySQL根据两行数据选择计数

时间:2013-05-27 15:46:26

标签: mysql

表列标题:n,t1,t2

条目:

1  A  B
2  A  C
3  B  C
4  D  E
5  B  A

如何计算每个字母在t1中出现的总行数减去它们在t2中出现的行数?我需要做一些事情,比如在1个查询中跟随2行:

select count(*) as val,t1 from table group by t1
select count(*) as val,t2 from table group by t2

谢谢, 马丁

2 个答案:

答案 0 :(得分:3)

这是一种方式:

select t1, max(t1cnt) - max(t2cnt) as diff
from ((select t1, count(*) as t1cnt, 0 as t2cnt
       from t
       group by t1
      ) union all
      (select t2, 0 as t1cnt, count(*) as t2cnt
       from t
       group by t2
      )
     ) t
group by t1

使用union all可确保您从两列获取所有可能的值,甚至是仅显示在一列中的值。

答案 1 :(得分:3)

您可以使用以下查询来获取结果。此查询首先获取所有不同t1t2值的列表(这是UNION查询)。获得这些值的列表后,就可以使用LEFT JOIN来处理您发布的原始查询:

select d.col, coalesce(totT1, 0) - coalesce(totT2, 0) Total
from
(
  select t1 col
  from entries
  union 
  select t2 col
  from entries
) d
left join
(
  select count(*) totT1, t1
  from entries
  group by t1
) d1
  on d.col = d1.t1 
left join
(
  select count(*) totT2, t2
  from entries
  group by t2
) d2
  on d.col = d2.t2;

请参阅SQL Fiddle with Demo