— table1 has 1 record
select * from t_test01 tid value 1 1.5
— table2 has 4 record
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 record
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 record
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
How to query the number of records when there is the DISTINCT keyword in the SQL multi-table join query string?
select COUNT(DISTINCT t_test01.tid, t_test02.value) ?? from t_test01, t_test02 where t_test01.value = t_test02.value
Advertisement
Answer
A quick-and-dirty approach is to use strings:
select count(distinct concat(t_test01.tid, '|', t_test02.value)) from t_test01 join t_test02 on t_test01.value = t_test02.value;
Otherwise, you can use a subquery or 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;
Note the use of proper, explicit, standard, readable JOIN
syntax in both cases. Never use commas in the FROM
clause.