计算mysql中两行之间的差异

时间:2016-10-10 06:16:34

标签: mysql

我有以下两个表 -

Table1

TR1 TR2
1   10
2   15
3   20

Table2

TC1 TC2
10  100
15  150
20  200

select count(*) from table1, table2 where table1.tr2 = table2.tc1 and table1.tr1 > 1 and table1.tr2 in (select table2.tc1 from table2 where table2.tc1 > 10)

select count(*) from table1, table2 where table1.tr2 = table2.tc1 and table1.tr1 > 1 and table1.tr1 < 5 and table1.tr2 in (select table2.tc1 from table2 where table2.tc1 > 10)

第二个查询将返回第一个查询的子集,我想找到两个查询给出的count(*)s的差异。我该怎么做呢?

2 个答案:

答案 0 :(得分:1)

你可以随时

select (select count(*) ...) - (select count(*) ...);

但是,由于您的查询非常相似,您可以合并查询:

select
  count(*) - sum(t1.tr1 < 5)
from table1 t1
join table2 t2 on t1.tr2 = t2.tc1 
where t1.tr1 > 1
and t1.tr2 > 10;

我已将逗号分隔的连接更改为正确的ANSI连接。您的连接语法在1992年变得多余。您不应再使用它了。

我已使用简单IN替换了您的t1.tr2 > 10条款,因为您已加入t1.tr2 = t2.tc1

答案 1 :(得分:0)

你可以这样做差异

 select (
      select count(*) 
      from table1, table2 
      where table1.tr2 = table2.tc1 
      and table1.tr1 > 1 
      and table1.tr2 in (select table2.tc1 from table2 where table2.tc1 > 10)
  ) - (
      select count(*) 
      from table1, table2 
      where table1.tr2 = table2.tc1
      and table1.tr1 > 1 
      and table1.tr1 < 5 
      and table1.tr2 in (select table2.tc1 from table2 where table2.tc1 > 10)
  )  as my_diff
from dual;