简体   繁体   English

可以使这个SQL查询更快?

[英]Possible to make this SQL query faster?

Just curious if it's possible to make this query any faster? 只是好奇是否可以更快地进行此查询? or if there is any other similar queries that would work better? 或者是否有任何其他类似的查询可以更好地运作?

SELECT id,source FROM posts
WHERE id = ANY(SELECT image_id FROM `post_tags` WHERE tag_id = (SELECT id FROM `tags` WHERE tag = _utf8 '$TAG' collate utf8_bin))
  AND posts.exists = 'n'
ORDER BY posts.ratecount DESC
LIMIT 0,100

Without using the: 不使用:

  AND posts.exists = 'n'
ORDER BY posts.ratecount
DESC LIMIT 0,100

It speeds up to query to usable levels, but somewhat need this for what I'm doing. 它加速查询到可用的级别,但有些需要我正在做的事情。

  • Tags table has unique index for both 'tag' and 'id'. 标签表具有“标签”和“标识”的唯一索引。
  • Tags has 83K rows. 标签有83K行。
  • Post_tags has unique index for 'image_id', 'tag_id'. Post_tags具有'image_id','tag_id'的唯一索引。 Also normal index for each. 也是每个的正常指数。
  • Post_tags has 471K rows. Post_tags有471K行。
  • Posts has unique index for 'id'. 帖子有'id'的唯一索引。 Also normal index for 'exists' and 'ratecount'. 也是'exists'和'ratecount'的正常索引。
  • Posts table has about 1.1M rows. 帖子表有大约1.1M行。

What is your TAG table look like? 你的TAG表是什么样的? Does it contain only ID and TAG fields? 它只包含ID和TAG字段吗? I would create a an unique index on TAG(TAG, ID) so the inner most query just searches an index. 我会在TAG(TAG, ID)上创建一个唯一索引TAG(TAG, ID)因此最内部的查询只搜索索引。

What about POST_TAGS table? POST_TAGS表怎么样? Is it just a combination of TAG_ID and IMAGE_ID? 它只是TAG_ID和IMAGE_ID的组合吗? Again, I would create an unique index on POST_TAGS(IMAGE_ID, TAG_ID) . 我再次在POST_TAGS(IMAGE_ID, TAG_ID)上创建一个唯一索引。

Just to note that order of fields in an index is important, and an index on POST_TAGS(TAG_ID, IMAGE_ID) differs much with an index on POST_TAGS(IMAGE_ID, TAG_ID) using in parsing plans. 只是要注意索引中的字段顺序很重要, POST_TAGS(TAG_ID, IMAGE_ID)上的索引与POST_TAGS(IMAGE_ID, TAG_ID)上的索引在解析计划中的区别很大。

And in the POSTS table having an unique index on POSTS(ID, POSTS, RATEACCOUNT) can help, (I know it is an redundant index, and make extra cost on INSERT, UPDATE and DELETE, but it will help you in this query). 并且在POSTS表中有一个唯一的POSTS索引POSTS(ID, POSTS, RATEACCOUNT)可以提供帮助,(我知道它是一个冗余索引,并且在INSERT,UPDATE和DELETE上产生额外成本,但它会在这个查询中帮助你) 。

By the way, using a JOIN in the inner query may give you performance gain, just check it. 顺便说一下,在内部查询中使用JOIN可以为您提供性能提升,只需检查即可。

Managed to get it working using a JOIN as someone suggested. 根据有人建议使用JOIN进行管理。

SELECT * FROM posts
LEFT JOIN post_tags ON post_tags.image_id = posts.id
JOIN tags ON post_tags.tag_id = tags.id
WHERE tags.tag = _utf8 '$tag' collate utf8_bin
  AND posts.exists = 'n'
ORDER BY posts.ratecount DESC
LIMIT 0,100

Reduced time taken from 22s > 0.26s. 减少从22秒> 0.26秒的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM