Reducing a normalized table to one value

Posted by Dio on Stack Overflow See other posts from Stack Overflow or by Dio
Published on 2011-01-14T16:45:40Z Indexed on 2011/01/14 16:53 UTC
Read the original article Hit count: 214

Filed under:

Hello,

I'm sure this has been asked but I'm not quite sure how to properly search for this question, my apologies.

I have two tables, Foo and Bar. For has one row per Food, bar has many rows per food matching descriptors.

Foo

name id
Apple 1
Orange 2

Bar

id description
1 Tasty
1 Ripe
2 Sweet

etc (sorry for the somewhat contrived example).

I'm trying to return a query where if, for each row in Foo, Bar contains a descriptor in ('Tasty', 'Juicy') return true ex:

Output

Apple True
Orange False

I had been solving this somewhat trivially with a case when I only had one item to match

select
Foo.name,
case bar.description
when 'Tasty' then True
else 'False'
end
from Foo
left join Bar on foo.id = bar.id
where bar.description = 'Tasty'

But with multiple items, I keep ending up with extra rows:

Output

Apple True
Apple False

etc etc

Can someone point me in the right direction on how to think about this problem or what I should be doing? Thank you.

© Stack Overflow or respective owner

Related posts about sql