使用shardingJdbc时,部分逻辑选择在数据库中处理
具体的语句有下面两条
1:select count(distinct field) from table
2: select field1,count(distinct field2) from table group by field1
第一次尝试
sharding无法解析count(distinct),寻找方法重写sql
以第一条举例子,首先写出来的是做子查询
with c as
(
select count(1) from table.a group by field
)
select count(1) from c;
在mysql中执行没问题,但是sharding依旧无法使用,因为它不能解析with as
第二次尝试
尝试修改with as,转成子查询的另一种写法
select temp.field1,count(distinct temp.field2) from
(
select field1,field2 from table
) as temp group by temp.field1
但是以上回来的结果不准确,不确定sharding具体是如何计算的,没有深挖继续换写法,使用临时表多个group by的写法:
select field1,count(1) from (
select field1 , field2 ,count(1)
from table
group by field1 , field2
)as a
group by field1
经过测试与语句2结果相同,