Search code examples
sqlmysql

Mysql query using in () doesn't work with a comma-separated value


I am trying to find all products that are connected with category list with this query:

SELECT p.id, product_name, added_date 
FROM products p, products_to_categories ptc 
WHERE ptc.category_id in ("89,88,83,87,84,85,86,82") 
AND ptc.product_id=p.id and p.active="1" 
group by p.id   

if I cut the condition AND ptc.product_id=p.id returns rows - wrong rows for active condition.. what is the correct way to get correct information with 1 query? - is it possible at all? thanks


Solution

  • Don't quote the list of category IDs:

    SELECT p.id, product_name, added_date 
    FROM products p
    JOIN products_to_categories ptc ON ptc.product_id=p.id
    WHERE ptc.category_id IN (89, 88, 83, 87, 84, 85, 86, 82) 
    AND p.active="1" 
    GROUP BY p.id