简体   繁体   English

如何优化双选查询

[英]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 我认为双重选择是不好的,但我是新来的MySQL

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

The optimization depends (I think) on the version of MySQL you are using. 优化取决于(我认为)取决于您使用的MySQL版本。

This is how you write it as a join : 这是您将其编写为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) . 我想到的是: articles(category_id, id)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. 您也可以将select的字段添加到第一个索引,因此可以通过查看索引而不是返回主表来满足整个查询。

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

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