所以,还是先保持在接口中远程调用吧。
这样看来,可以优化的地方只能在:for循环中查询数据。
3. 第一次优化
由于需要在for循环中,每条记录都要根据不同的条件,查询出想要的数据。
由于业务系统调用这个接口时,没有传id ,不好在where 条件中用id in (...),这方式批量查询数据。
其实,有一种办法不用循环查询,一条sql就能搞定需求:使用or 关键字拼接,例如:(org_code='001' and category_id=123 and business_id=111 and business_type=1) or (org_code='002' and category_id=123 and business_id=112 and business_type=2) or (org_code='003' and category_id=124 and business_id=117 and business_type=1)...
这种方式会导致sql语句会非常长,性能也会很差。
其实还有一种写法:
where (a,b) in ((1,2),(1,3)...)
不过这种sql,如果一次性查询的数据量太多的话,性能也不太好。
居然没法改成批量查询,就只能优化单条查询sql的执行效率了。
首先从索引入手,因为改造成本最低。
第一次优化是优化索引。
评价表之前建立一个business_id字段的普通索引,但是从目前来看效率不太理想。
由于我们果断加了联合索引:
alter table user_score add index `un_org_category_business` (`org_code`,`category_id`,`business_id`,`business_type`) USING BTREE;
该联合索引由:org_code、category_id、business_id和business_type四个字段组成。
经过这次优化,效果立竿见影。
批量评价查询接口最大耗时,从最初的20s ,缩短到了5s左右。