简体   繁体   English

有什么比合并3个表更好的方法?

[英]What is the better way than joining 3 tables?

I have to join 3 tables somewhere on my project. 我必须在项目的某处加入3个表。
Here is example tables and columns: 这是表格和列的示例:

Table-1 : posts 
Columns1: id,owner,title,post,keywords

Table-2 : sites
Columns2: id,name,url

Table-3 : views
Columns3: id,post,view

When I join all these tables it happens such a little huge query: 当我加入所有这些表时,会发生一些巨大的查询:

SELECT title,post,keywords,name,url,view
FROM posts 
LEFT JOIN sites ON sites.id=posts.owner 
LEFT JOIN views ON views.post = post.id 
WHERE posts.date BETWEEN '2010-10-10 00:00:00' AND '2010-11-11 00:00:00' 
ORDER BY views.view DESC 
LIMIT 0,10

Is it the only way or could I do something else to get better performance? 是唯一的方法还是我可以做些其他事情以获得更好的性能?

This is my current query's EXPLAIN. 这是我当前查询的解释。 Above one is just an example. 以上只是一个例子。 MysqlFront EXPLAIN结果

That's not a particularly "Huge" query. 这不是一个特别的“巨大”查询。 Have you ran query analyzer and checked for where the slow point is and then checked your indexes? 您是否已运行查询分析器并检查了慢点在哪里,然后检查了索引?

Re: Analyzer - Microsoft keeps moving it, but in 2008 Management Studio there are several options for showing the execution plan. 回复:分析器-Microsoft一直在移动它,但是在2008 Management Studio中,有几个选项可以显示执行计划。 Once you see the execution plan you can see where the problems are. 一旦看到执行计划,就可以看到问题出在哪里。 Look for a single action taking 80+% of your time and focus on that. 寻找一个占用您80%以上时间的动作,并专注于此。 Things like Table Scans are an indication that you could speed it up by tweaking indexes. 诸如表扫描之类的事情表明您可以通过调整索引来加快速度。 (There are downsides to indexes as well, but worry about that later). (索引也有缺点,但稍后再担心)。

That's not a huge query by any stretch of the imagination. 凭空想想,这并不是一个巨大的疑问。

How slow is it really? 真的有多慢?

Maybe if views doesn't contain any more information than what you've shown, you should just have a view count be a field of posts. 也许如果视图所包含的信息不超过所显示的信息,那么您应该只将视图计数作为帖子字段。 No need for it to be its own separate table unless you're actually storing some information about the views themselves, like user-agent strings or time. 除非您实际上存储的是有关视图本身的某些信息,例如用户代理字符串或时间,否则不需要将其作为自己的单独表。

如果您的POSTS表特别大(> 10万行?),那么您可以做的一件事是将经过时间过滤的帖子加载到临时表中并加入该临时表。

If your relations are guaranteed, in other words non-nullable foreign keys, then the query will perform better if it uses inner joins instead of left joins. 如果您的关系得到保证,换句话说,就是不可为空的外键,那么如果查询使用内部联接而不是左联接,则查询性能会更好。 Although this query does not appear to be large or complex enough to seriously be suffering from performance issues. 尽管此查询看起来不足够大或复杂,以至于严重遭受性能问题的困扰。

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

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