简体   繁体   中英

How to optimize double select query

SELECT  `id`, `field2`, `field3`, `field4` as Title FROM `articles` 
WHERE `category_id` = 'X' 
AND `id` NOT IN 
(SELECT `articleid` FROM `article-seen` WHERE `userid` = 'Y')

How can I optimize this? I think double select is bad, but im new to mysql

尝试使用JOIN将获得相同的结果,但使查询看起来更简单

The optimization depends (I think) on the version of MySQL you are using.

This is how you write it as a join :

SELECT  `id`, `field2`, `field3`, `field4` as Title
FROM `articles` a left outer join
     `articles_seen` arts
     on a.id = arts.articleid and arts.userid = 'Y'
where a.`category_id` = 'X' and
      arts.id is null;

This query, at least, doesn't materialize the subquery, which (I think) your originally query would.

To makes this faster, you want to add indexes. The ones that come to mind are: articles(category_id, id) and articles_seen(userid, articleid) . You could also add the fields in the select to the first index, so the entire query can be satisfied by looking at the index, rather than returning to the main table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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