简体   繁体   中英

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:

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. You need to change that to a 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

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