2

I'm sure this is simple but my brain just isnt working today!

I have a table products, lets just assume it contains p_id, i have another table - a pivot table - which references between products and another table attributes, this table is products_to_attributes and contains pta_aid (attribute id) and pta_pid (product id)

Hopefully this (incorrect) query will show what i want to do better than i can explain it:

SELECT `p_id` FROM `products` 
LEFT JOIN `products_to_attributes` ON (`pta_pid` = `p_id`)
WHERE ((`pta_aid` = '1' OR `pta_aid` = '2') AND(`pta_aid` = '3'))

I want to be able to group together attributes where a product must have attribute 1 Or attribute 2 AND have attribute 3.

1
  • 2
    same field in same row can not have two values Commented Apr 1, 2011 at 11:25

2 Answers 2

2

If I understand your need correctly, you pretty much have to have two EXISTS clauses:

SELECT p_id FROM products PR
WHERE EXISTS (SELECT p_id FROM products_to_attributes WHERE (pta_aid = 1 OR pta_aid=2) AND pta_pid=PR.p_id )
AND EXISTS (SELECT p_id FROM products_to_attributes WHERE pta_aid = 3 AND pta_pid=PR.p_id)
Sign up to request clarification or add additional context in comments.

Comments

0
SELECT p.`p_id` FROM `products` p
LEFT JOIN `products_to_attributes` pta ON (p.`p_id` = pta.`pta_pid`)

Name the tables and specify which field is from which table. However how a field can be both 1 and 3 in a row? there is a logical problem in your where clause.

1 Comment

I appreciate the logic problem but my code was essentially pseudo-code to explain the issue

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.