-
一个连表查询的优化
普通类 -
- 支持
- 批判
- 提问
- 解释
- 补充
- 删除
-
-
需求描述
有3张表,一张表存放作文信息,一张存放成语信息,一张存放作文-成语对应信息,作文表中有10多万条记录,1篇文章对应N个成语,1个成语对应N个文章。想实现根据不同年级显示成语引用情况,并实现成语引用次数的排序。
作文表结构如下:
作文-成语信息对应表结构如下:
-
解决思路
思路1:采用原生sql,先对作文-成语表进行group by idiomId,即先选择idiomID的多少排序,然后再对比找出的articleId是否在作文表中,结果发现查询速度极慢,一个查询耗费10多s甚至更多,不是个好的办法。sql查询语句大致如下:
- select idiomId,articleId, count(*) as numbers from lcell_article_idiom group by idiomId having articleId in(select id from lcell_article where theme="
- + theme + ") order by numbers desc "
思路2:采用视图,及先从作文表中选出不同年级的作为,sql语句如下:
- create view article_idiom_grade12 as select a.articleId,a.idiomId,b.theme from lcell_article_idiom as a, lcell_article as b where a.articleId=b.id having a.articleId in(select id from lcell_article where grade =12);
然后再从视图中查询,发现速度仍是很慢,百度后发现要对建立视图的表建立索引,发现速度仍是不够理想
思路3:将生成的视图直接转换成表,然后在查询,sql语句如下:
- //建立视图
- create view article_idiom_grade12 as select a.articleId,a.idiomId,b.theme from lcell_article_idiom as a, lcell_article as b where a.articleId=b.id having a.articleId in(select id from lcell_article where grade =12);
- //拷贝表
- create table article_idiom_grade_9 as select * from article_idiom_grade9;
- //创建查询
- if (grade > 0) {
- if (theme > 0) {
- sql = "select idiomId, count(*) as numbers from article_idiom_grade_"
- + grade
- + " where theme = "
- + theme
- + " group by idiomId order by numbers desc ";
- countSql = "select count(idiomId) from (select DISTINCT idiomId from article_idiom_grade_"
- + grade
- + " where theme ="
- + theme
- + ") lcell_article_idiom";
- } else {
- sql = "select idiomId, count(*) as numbers from article_idiom_grade"
- + grade + " group by idiomId order by numbers desc ";
- countSql = "select count(idiomId) from (select DISTINCT idiomId from article_idiom_grade_"
- + grade + " ) lcell_article_idiom";
- }
- }
速度减少到2s左右,勉强能接受了。。。
大家有更好的办法就话我知一下~thx~
-
-
- 标签:
- 查询
- 需求
- 成语
- 作文
- 一个
- 发现
- 速度
- 优化
- 视图
- idiomid
- 思路
- sql
-
学习元评论 (0条)
聪明如你,不妨在这 发表你的看法与心得 ~