0

Thanks in advance for the help.

I have a table labelled attributes. In that table is product item numbers (pin), and attribute numbers. Each attribute for a pin is in a separate row

Ex.

pin   attribute
111     4
111     5
111     10
112     4
112     5
...

I am trying to find a query that will allow me to say "Select pin if attribute = 4 and attribute = 5"

The attributes would be color, size, etc.. so get all records that are red (4) and size Small (5).

In the example above, it would return pins 111 and 112.

Mike

1
  • are you still having problem with this query? Commented Aug 6, 2013 at 4:00

3 Answers 3

1

This should work for you using count with distinct:

select pin 
from attributes
where attribute in (4,5)
group by pin
having count(distinct attribute) = 2

This will return any pins that have both attributes 4 and 5.

Sign up to request clarification or add additional context in comments.

1 Comment

@user2579643 -- np, glad I could help!
0

This is an example of a "set-within-sets" query. I advocate doing this with aggregation and a having clause. For your example, this would look like:

select pin
from attributes
group by pin
having sum(attribute = 4) > 0 and
       sum(attribute = 5) > 0;

The reason I like this approach is because it is flexible. If you wanted attributes 4 or 5, the query would be:

having sum(attribute = 4) > 0 or
       sum(attribute = 5) > 0;

If you wanted 4 and 5 and nothing else:

having sum(attribute = 4) > 0 and
       sum(attribute = 5) > 0 and
       sum(attribute not in (4, 5)) = 0;

Comments

0
select pin,
group_concat(distinct attribute order by attribute) as atts 
from attributes
where attribute in (4,5)
group by pin
having (atts = '4,5');

fiddle

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.