简体   繁体   English

MySQL-瓶颈-加入一对多,新闻文章标签

[英]MySQL - Bottleneck - Join one to many, Tags of news articles

I have a news section. 我有一个新闻版块。 Articles are tagged and stored in 3 tables: 文章被标记并存储在3个表格中:

posts: 帖子:

posts_id,title,body

tags: 标签:

tags_id,name

posts_tags: posts_tags:

posts_id,tags_id

The problem at the moment is that the front page of the news section displays previews of the first 10 articles. 目前的问题是新闻部分的首页显示了前10篇文章的预览。 Each preview displays the tag lists. 每个预览都会显示标签列表。 Displaying the tag lists means I have to query again for each post to get a list of the tags. 显示标签列表意味着我必须再次查询每个帖子以获取标签列表。

So for example, the 10 previews requires, 1 query(gets 10 posts from posts)+10 queries(1 for each post on tags and posts_tags to get tag lists). 因此,例如,10个预览需要1个查询(从帖子中获取10个帖子)+10个查询(对于tag和posts_tags上的每个帖子1个,以获取标签列表)。 11 queries to load a page seems like it could eventually be a bottleneck. 加载页面的11个查询似乎最终可能成为瓶颈。

Should I forgo tagging previews? 我应该放弃标记预览吗? Would PIVOT result in the same amount of queries? PIVOT是否会导致相同数量的查询?

I see 2 main solutions you could try: 我看到您可以尝试的2种主要解决方案:

  • Make your code to do all in one query (return each post with related tags using a join) 使您的代码可以在一个查询中完成所有操作(使用联接返回每个带有相关标签的帖子)

  • Use a Cache layer between the web server and the scripting language, so if the page doesn't change, it doesen't makes all the querys again 在Web服务器和脚本语言之间使用Cache层 ,因此,如果页面没有更改,则不会再次进行所有查询

You can use a "join" to keep it all in one query. 您可以使用“联接”将其全部保留在一个查询中。 However: these kind of queries can get very "expensive", escpecially if you are going to do some kind of grouping. 但是:这类查询会变得非常“昂贵”,特别是如果您要进行某种分组的话。 So i would recommend to experiment with subselects. 因此,我建议尝试使用子选择。 For example: 例如:

SELECT (
    SELECT GROUP_CONCAT(name)
    FROM   tags, posts_tags
    WHERE  posts_tags.posts_id = posts.posts_id
    AND    tags.tags_id = posts_tags.tags_id
) FROM posts LIMIT 10

With such kind of subselects you can normally get much better results than doing a normal join and grouping. 使用这种子选择,通常可以获得比进行常规联接和分组更好的结果。

Caching is of course still a good idea ... 缓存当然仍然是一个好主意...

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

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