简体   繁体   English

改进SQL查询以排除项目

[英]Improve sql query to exclude items

Is it possible to improve the following query : 是否可以改善以下查询:

SELECT * 
FROM   search s left join search_criteria sc ON s.id = sc.search_id
WHERE  sc.deleted_at IS NOT NULL 
AND    s.id NOT IN
        (  SELECT s.id
           FROM   search s
                    left join search_criteria sa ON s.id = sc.search_id
           WHERE sc.deleted_at IS NULL
        )
GROUP BY s.id

Thanks 谢谢

It depends - if the default database is kelformation, then I think your query effectively simplifies to: 这取决于-如果默认数据库是kelformation,那么我认为您的查询实际上可以简化为:

SELECT  * 
FROM    search s left join search_criteria sc ON s.id = sc.search_id
WHERE   sc.deleted_at IS NOT NULL 
GROUP BY s.id

Think about the next scenario: 考虑下一个场景:

You have a box full of marbles. 你有一个装满大理石的盒子。 What will be faster? 什么会更快?

  • Showing the entire box (Just spill it on the table) 显示整个盒子(只需将其洒在桌子上)

  • Or showing only the marbles with green dots (You need to examine each individual marble before showing it). 或仅显示带有绿色点的大理石(在显示每个大理石之前,您需要对其进行检查)。

Now, it seems you must exclude, so you have to go with it. 现在,看来您必须排除在外,因此您必须继续使用它。
MySql has issues with inner queries. MySql内部查询有问题。 You need to change that to a LEFT JOIN. 您需要将其更改为LEFT JOIN。
Provide your schema for a more detailed answer. 提供您的架构以获得更详细的答案。

Try this :: 尝试这个 ::

SELECT * 
FROM   search s
          left join search_criteria sc ON s.id = sc.search_id
          left join kelformation.search ks on (s.id=ks.id)
          left join search_criteria sa ON ks.id = sa.search_id
WHERE  sc.deleted_at IS NOT NULL and sc.deleted_at IS NULL 
AND    /*Primary key of kelformation.search */ is null
GROUP BY s.id

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

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