简体   繁体   中英

MySql Query Optimisation, replacing not in subquery with join

I have a query that I feel is very bulky and can do with optimisation. First thing would obviously be replacing not in subquery with join but it affects the sub-sub query that I have. I'd appreciate suggestions/workaround on it.

This is the query

SELECT *
FROM lastweeksales
WHERE productID =  1234
AND retailer NOT 
IN (
    SELECT retailer
    FROM sales
    WHERE productID
    IN (
        SELECT productID
        FROM products
        WHERE publisher = 123
    )
    AND DATE =  date(now())
)

Basically, I want to get rows from lastweek's sales on a product where retailers are not present that did sales today but sales should only be on products by a certain publisher.

:S:S:S

You can group together 2 inner subqueries easily via INNER JOIN . For the outer one you should use LEFT OUTER join and then filter on retailer IS NULL , like this:

SELECT lws.*
  FROM lastweeksales lws
  LEFT JOIN (SELECT s.retailer 
               FROM sales s
               JOIN products p USING (productID)
              WHERE p.publisher = 123
                AND s.date = date(now())) AS r
         ON lws.retailer = r.retailer
 WHERE r.retailer IS NULL;

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