SQL多表连接查询字符串中有DISTINCT关键字时如何查询记录数?

时间:2021-07-13 03:00:51

标签: sql sql-server

-- table1 有 1 条记录

select * from t_test01

tid    value   
1      1.5

-- table2 有 4 条记录

select * from t_test02

tid    value   
1      1.5
2      1.54
3      1.5
4      1.5

-- t_test01.value = t_test02.value, 3 条记录

select t_test01.tid, t_test02.value
from 
t_test01, t_test02
where 
t_test01.value = t_test02.value

tid    value
1      1.5
1      1.5
1      1.5

-- DISTINCT t_test01.value = t_test02.value,1 条记录

select DISTINCT t_test01.tid, t_test02.value
from 
t_test01, t_test02
where 
t_test01.value = t_test02.value

tid    value
1      1.5

SQL多表连接查询字符串中有DISTINCT关键字时如何查询记录数?

select COUNT(DISTINCT t_test01.tid, t_test02.value) ??
from 
t_test01, t_test02
where 
t_test01.value = t_test02.value

2 个答案:

答案 0 :(得分:1)

使用子查询:

为了清楚起见,我重写了查询,但您可以使用任何查询:

  WITH T AS (
       select DISTINCT t1.tid, value 
       from 
       t_test01 t1 JOIN t_test02 t2  USING (value)
       )
       SELECT count(*) from T;

答案 1 :(得分:1)

一种快速而肮脏的方法是使用字符串:

select count(distinct concat(t_test01.tid, '|', t_test02.value))
from t_test01 join
     t_test02 
     on t_test01.value = t_test02.value;

否则,您可以使用子查询或 CTE:

select count(*)
from (select distinct t_test01.tid, t_test02.value
      from t_test01 join
           t_test02 
           on t_test01.value = t_test02.value
     ) t;

注意在这两种情况下都使用正确、明确、标准、可读的 JOIN 语法。 从不FROM 子句中使用逗号。