我现在有一张表,没有主键,只有一个联合唯一 (date,user_id,count_name, )
表格记录示例: date:20160808 user_id:556 count_name: a1date表示日期,user_id 表示用户的id , count_name 表示某一个统计值。
count_name 可取值 (a1,a2,a3,···,a12,b1,b2,b3,···,b12);
每天产生的记录有几万条。
数据库每次取出记录上限1万条。
我现在需要统计12个值。 用mysql语句可以这么表示:
select count(distinct(`shop_id`)) from count_table where date = '20160808' and count_name in ('a1','b1');
select count(distinct(`shop_id`)) from count_table where date = '20160808' and count_name in ('a2','b2');
···
这样取12次数据库,可以达到结果,但效率不高。
请问有没有方法可以一次取出想要的数据呢?(这是一个比较老的数据库,数据量比较大,修改数据库什么的做最后的考虑哈!)
尝试过的方法:
分页统计的话,由于表格没有主键,分页不好处理。
一次性取出数据在处理,受制于mysql一次只能取出1万条左右的数据,再多可能就崩溃了。
可以用CASE WHEN的写法,访问一次数据库就可以了
select count(distinct(id_1)), count(distinct(id_2)), count(distinct(id_3))
from (
select
case when count_name in ('a1','b1') then shop_id else null end as id_1 ,
case when count_name in ('a2','b2') then shop_id else null end as id_2 ,
case when count_name in ('a3','b3') then shop_id else null end as id_3
from count_table
where date = '20160808'
)
直接分析数据源效率不高的情况下,建议将数据源的数据转换到专门用于分析的数据库(或表)中,再进行分析。
select count(distinct(`shop_id`)) from count_table where date = '20160808' and count_name in ('a1','b1')
union all
select count(distinct(`shop_id`)) from count_table where date = '20160808' and count_name in ('a2','b2')
...;
这种方式其实也是执行12次,便一个语句可以搞定,可以试下
另外,分页取出,然后在程序里统计也是可以考虑的,虽然没有主健,但有唯一索引,你可以试下
order by date asc, userid asc, count_name asc
分页条件:
where date >= #{上次分页最后一条记录的DATE} and userid >= #{上次分页最后一条记录的userid} and count_name>#{上次分页最后一条记录的count_name}
limit #{page_limit}
没啥好办法,in的效率本来就低,还是改表结构靠谱点,