以内存换sql查询效率 思想

假如:

account用户表:14w+条数据;字段:account_iddescription  等;description允许为空

account_stat用户统计表:14w+条数据;字段:account_idnum 

需要找出:按num从高到低的,且description不等于“医生”、“护士”的30条数据


看似很简单,但是。。。。。。

一般想法会想到用not in或者and两个不等于<>

select * from account a,account_stat s where a.account_id=b.account_id and a.description not in('医生','护士') order by s.num desc

或者

select * from account a,account_stat s where a.account_id=b.account_id and a.description <>'医生' and a.description <>'护士' order by s.num desc


如果是这样的话,那么就死死的掉到not in<>的陷阱里面去了,因为innot in并非互补,=<>也并非互补

select count(*)  from account             -------输出 140605条记录

select count(*)  from account where description in('医生','护士')   -------输出 196条记录

select count(*)  from account where description not in('医生','护士')   -------输出 10044条记录

你会发现innot in的结果加起来并不等于总数的,所以用not in 就会出bug了;<>也类似。


那么,我们就会想到用not exists

先符合description条件的:

select account_id from account a where not exists(select * from account b where a.account_id=b.account_id and b.`description` in('资深专家','专业编辑'))

可看出这里相当于查了两个表:14W+ * 14w+


然后再让num从高到低排序,取30条,由于numaccount_stat表的,故这里又需要连接两个表,又是 14w+ * 14w+ 的数据


可以想象得到,得出来的结果相当于414w+的表连接起来的查询结果,执行效率相当低。如果一个该数据每天都需要执行好几遍,那么就必须提高效率了。以下提供了一种以内存换效率的思想:

500条数据存于list-->加专家条件-->30条数据存数据库(fk_rise_top)-->回收list


实现思路:

从数据库中取500条数据,取出的数据通过rowmapper实现数据库字段与entity(该entity为临时用,并非数据库中真实存在的表)的匹配,然后存于list中;

写公共方法以实现description条件的match

match合适的30条数据存于另一个lis

把该list的数据存于数据库;

手动回收list


【这样的思路:其实就是把原来需要在sql中进行完成的工序修改到用内存完成,可以大大加快sql的查询速度。相当于就是:用内存换效率,故操作完后需要立马手动释放内存,回收list

你可能感兴趣的:(思想,以内存换sql查询效率)