0

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

3
  • what is the datatype of active column? Commented Mar 2, 2014 at 10:41
  • active is enum('0', '1') Commented Mar 2, 2014 at 10:42
  • It's generally a bad idea using numeric strings in an ENUM. Commented Mar 2, 2014 at 10:43

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

guys, I removed the quotes and get 1 extra row, but still not full correct results, I tryed @Barmar's query and still.. what else could be?
Please post some sample data and the expected results.
your query is OK, just my fault with copy /paste.. I accept it as answered, thank you
1

Try removing quoting in IN clause and in p.active if active is int/bool

$q='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';

Comments

0

Dont encapsulate all categories with brackets. MySQL interprets this as a single category. Encapsulate each category, e.g. "89","90","91". You can also just skip the brackets altogether as it is integers you query on.

You would encapsulate the ids if they were strings, e.g. "one","two","three".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.