Pretty bad at MySQL as I’ve only done light web design and SQL on oracle dbs. Say I have a table listing all the fruits people like.
name fruit
------------
john bananas
john oranges
marcy bananas
dave oranges
lucy bananas
lucy oranges
Say I wanted to get all the names of people that liked oranges but didn’t specify if they liked bananas. There’s only two possible fruits in this table. (It may expand to more but there are generally only two).
What would the query be? I want a query that only returns “dave” because marcy has only specified she likes bananas, and john and lucy say they like both. I don’t think I need a join since this is only one table.
I’m trying
select name from table
where(--uhm.. use the stuff below somehow
select name from table
where fruit like 'bananas';
select name from table
where fruit like 'oranges';
)
I would also be really happy with a query that returned all the people that like oranges but not bananas, or bananas but not oranges instead. I don’t know which query would be easier.
Also I’m sure I’d be able to find someone else with the same problem on the internet. What query would you use on google to answer my question?
I suppose this should do the trick:
This query is better read from within:
NOT INnested query) you collect all the names of people not liking some specific fruit (let’s call them “fruit-haters”)We have to use either nested query or join here, as a single row doesn’t have all information about someone’s favorite fruits. And, actually,
DISTINCTis not required in this particular case – but will be useful, if(name, fruit)combination is notUNIQUE.Here’s SQL Fiddle to play with. And here’s quite a helpful article comparing (performance-wise) several ways of achieving the same result.