1
SELECT products.name from products WHERE products.id 
NOT IN ( SELECT DISTINCT(products.id) FROM timer_completed
INNER JOIN com_jobcard ON com_jobcard.id = timer_completed.job_card_id
INNER JOIN products ON products.id = com_jobcard.product_id)

In the above query SELECT DISTINCT(products.id) FROM timer_completed will return multiple values but I need the products which are not in that result set, so I have used NOT IN function but it returns error. Could you suggest me a better way to achieve this.

Saurabh
  • 71,488
  • 40
  • 181
  • 244
user1894647
  • 613
  • 3
  • 11
  • 22

3 Answers3

0

I suspect your sub-query returns some NULL values which will make the NOT IN to fail(will not throw error). Use NOT EXISTS to do this

SELECT products.NAME 
FROM   products p 
WHERE  NOT EXISTS (SELECT 1 
                   FROM   timer_completed 
                          INNER JOIN com_jobcard 
                                  ON com_jobcard.id = timer_completed.job_card_id 
                   WHERE  p.id = com_jobcard.id) 
Community
  • 1
  • 1
Pரதீப்
  • 91,748
  • 19
  • 131
  • 172
0

USE NOT EXISTS instead of NOT IN. I hope this will work..

NOT IN operation would fail if the result set being probed returns a NULL. In such a case, the results of a NOT IN query is 0 rows while a NOT EXISTS query would still show the rows present in the one table but not in the other table.

Bhanu Chandra
  • 408
  • 8
  • 26
0

The best way to search for missing values in MySQL is using a LEFT JOIN / IS NULL or NOT IN rather than NOT EXISTS.

You can make use of LEFT JOIN here.

SELECT P.name
FROM 
    products P
LEFT JOIN 
     (SELECT DISTINCT(products.id) FROM timer_completed
      INNER JOIN com_jobcard ON com_jobcard.id = timer_completed.job_card_id
      INNER JOIN products ON products.id = com_jobcard.product_id) T
     ON P.product_id <> T.product_id
WHERE T.product_id IS NULL

Hope this helps.

Subin Chalil
  • 3,531
  • 2
  • 24
  • 38