简体   繁体   English

使用JOIN提高SQL查询性能

[英]Improve SQL Query performance with JOIN

I've got the following, slow performing, SQL query: 我有以下,性能低下的SQL查询:

SELECT *
FROM news_events
WHERE 1 AND (user_id = 2416) OR id IN(SELECT content_id FROM likes WHERE user_id = 2416)
ORDER BY id DESC
LIMIT 0,10

The news_events table has indexes on user_id. news_events表在user_id上有索引。 And the likes table has an index on user_id. likes表在user_id上有一个索引。

To try to improve performance I have re-written the query using an INNER JOIN the following way: 为了提高性能,我使用INNER JOIN以下列方式重写了查询:

SELECT a.*
FROM news_events a
INNER JOIN likes b ON (a.id = b.content_id)
WHERE (a.user_id = 2416) OR (b.user_id = 2416)
ORDER BY a.id DESC
LIMIT 0,10

But performance doesn't improve either. 但性能也没有改善。 I've run explain on this last query and this is the result: 我在最后一个查询上运行了解释,结果如下:

mysql解释

I appreciate any pointer on what I could do to improve the performance of this query. 我很欣赏任何指针,我可以做些什么来提高这个查询的性能。

SELECT *
FROM 
(
    SELECT a.* 
    FROM news_events a 
    WHERE a.user_id = 2416
    UNION
    SELECT ne.* 
    FROM news_events ne 
        INNER JOIN likes l 
            ON ne.id=l.contentid 
    WHERE l.user_id = 2416
)
ORDER BY 1 DESC
LIMIT 0,10

Try this query - 试试这个查询 -

SELECT * FROM news_events ne
LEFT JOIN (SELECT content_id FROM likes WHERE user_id = 2416) l
  ON ne.user_id = 2416 OR ne.id = l.content_id
ORDER BY
  ne.id DESC
LIMIT
  0, 10

These columns should be indexed: news_events.user_id , news_events.id , likes.user_id , likes.content_id . 应该为这些列编制索引: news_events.user_idnews_events.idlikes.user_idlikes.content_id

Your query is quite good enough. 你的查询非常好。 Posted queries by mates are also fine. 配偶发布的查询也没问题。 But, if you are having large set of data and you did not rebuild indexes since long then, you need to rebuild indexes on both tables. 但是,如果您拥有大量数据并且从那时起您没有重建索引,则需要在两个表上重建索引。

It is a standard protocol that db admin need to rebuild all the indexes timely as well as recompile all the objects+packages in the db. 这是一个标准协议,db admin需要及时重建所有索引,并重新编译db中的所有对象+包。

I hope it will help :) Keep querying! 我希望它会有所帮助:)继续查询!

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

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