I have a table profile_data, structured like this:
id, user_id, field_id, value
I need to get user_id for any users that have a match one of several zipcodes and their country is United States.
So far I have this non-working query:
SELECT data1.user_id
FROM profile_data data1, profile_data data2
WHERE data1.field_id = 80
AND ( value = '94114' OR value = '94146' OR value = '94117' )
AND data2.field_id = 90
AND value = 'United States'
Here’s my take on what you might be trying to do:
EDIT
I’m sorry, I didn’t realize that there might be multiple rows per user. If that is the case then the above won’t work. The edited exists statement in the answer above will. although you don’t need to do both as subqueries:
Hopefully your optimizer will reduce it to the correct number of joins anyway.
As an aside, zip codes are country-specific. So this specific example is redundant, but there are plenty of valid use-cases.