【发布时间】:2015-02-09 23:29:09
【问题描述】:
因此,此查询目前在网上商店中用于检索有关文章的技术数据。 除了最近显示的产品数量增加导致某些类别的加载时间过长之外,它已经很好地发挥了作用。
对于最糟糕的页面之一,此(以及其他一些查询)被请求大约 80 次。
我最近才知道 MySQL 不会将没有依赖参数的子查询优化为只运行一次。
因此,如果有人可以帮助我解决其中一个查询并解释如何将 in 和 exists 替换为 join,我可能会自己更改其他查询。
select distinct criteria.cri_id, des_texts.tex_text, article_criteria.acr_value, article_criteria.acr_kv_des_id
from article_criteria, designations, des_texts, criteria, articles
where article_criteria.acr_cri_id = criteria.cri_id
and article_criteria.acr_art_id = articles.art_id
and articles.art_deliverystatus = 1
and criteria.cri_des_id = designations.des_id
and designations.des_lng_id = 9
and designations.des_tex_id = des_texts.tex_id
and criteria.cri_id = 328
and article_criteria.acr_art_id IN (Select distinct link_art.la_art_id
from link_art, link_la_typ
where link_art.la_id = link_la_typ.lat_la_id
and link_la_typ.lat_typ_id = 17484
and link_art.la_ga_id IN (Select distinct link_ga_str.lgs_ga_id
from link_ga_str, search_tree
where link_ga_str.lgs_str_id = search_tree.str_id
and search_tree.str_type = 1
and search_tree.str_id = 10132
and EXISTS (Select *
from link_la_typ
where link_la_typ.lat_typ_id = 17484
and link_ga_str.lgs_ga_id = link_la_typ.lat_ga_id)))
order by article_criteria.acr_value
我认为这是带有子子查询的主要坏人
我只是注意到我可以删除最后一个存在并且仍然得到相同的结果,但速度没有增加,虽然不是问题的一部分;)我会弄清楚我是否仍然需要那个部分。
感谢任何帮助或指点,如果我遗漏了一些有用的信息,请告诉我。
【问题讨论】:
-
优化这种多表查询的第一步是重构它以更改连接样式。从
FROM tab1,tab2 ... WHERE ... tab1.col1 = tab2.col2样式更改为FROM tabl JOIN tab2 ON tab1.col1 = tab2.col2样式。陌生人(比如 SO 上的我们)更容易以这种方式看到逻辑。 -
另外,建议使用别名:
from article_criteria->from article_criteria ac,然后使用ac.acr_value而不是article_criteria.acr_value。同一个思路——不必将表名放在列名中——cri_id可以简单地为id。当有表前缀criteria.cri_id时,就像criteria.id一样可读。查询的大小可以减少 30% 甚至更多。 -
谢谢 ^^ 我会记住的,这是我第一个使用 MySQL 的大型项目。学习清理代码 MySQL 在即将到来的最后期限内有些受苦;)并且我在原始查询中遗漏了表名,但为了将问题放在这里,我添加了它们。否则外人更难看到信息属于哪个表
标签: mysql join inner-join exists