1

What is wrong with this query:

SELECT `product`.`id`, `title` AS `text` FROM `product` 
LEFT JOIN `productlang` ON product.id=productlang.product_id 
LEFT JOIN `new_product` ON product.id=new_product.product_id 
WHERE (`product`.`id` <> `new_product`.`product_id`) 
AND (`title` LIKE '%nik%') 
AND (`language`='bg') 
LIMIT 20

The purpose is to get all products from product table whose id doesn't exist in new_product (product_id is the related column).I tought WHERE (product.id <> new_product.product_id) part should do the trick. Where is my bad ? Thank you!

Toma Tomov
  • 1,476
  • 19
  • 55

1 Answers1

1
  • Whenever using Left Join, please ensure that your Where conditions on the right-side table of a Left Join are specified in the On clause. Otherwise, this would limit your result-set.
  • To check if there is no matching entry in the right-side table, we can use IS NULL.
  • Please use proper aliasing when dealing with multi-table queries, for readability and clarity purposes.

Try the following:

SELECT p.id, 
       pl.title AS `text` 
FROM product AS p 
LEFT JOIN productlang AS pl  
  ON p.id = pl.product_id AND 
     pl.title LIKE '%nik%' AND 
     pl.language = 'bg' 
LEFT JOIN new_product AS np 
  ON p .id = np.product_id 
WHERE np.product_id IS NULL 
LIMIT 20
Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57