Tables:
tUsers: userid (contains user info) tPrefs: prefid, prefname (contains preference definitions) tPrefVals: userid, prefid, value (contains preference values)
Preferences are not required, so a preference record may not actually exist.
the prefs table looks like:
id, userid, prefid, value
1, 1, 20, es
2, 1, 224, false
3, 1, 234, true
4, 2, 220, en
5, 2, 221, es
6, 2, 234, true
the prefid is the key to a preference definition, say a preference for primary language, secondary language, etc. the pref values table may or may not have a row corresponding to each preference defined in the tPrefs table. Make sense?
the values are all stored in the tPrefVals table. just there is one row in that table per pref per user, not just one row per user with multiple prefs.
Goal:
Get a list of users where who have the preference 20 or 21 set to a value of ‘es’.
SELECT DISTINCT tUsers.userid FROM tUsers
LEFT JOIN tPrefVals AS pri_lang ON tUsers.userid = pri_lang.user_id
LEFT JOIN tPrefVals AS sec_lang ON tUsers.userid = sec_lang.user_id
WHERE
((pri_lang.prefid = '20' AND pri_lang.value = 'es')
OR
(sec_lang.prefid = '21' AND sec_lang.value = 'es'))
My thought was to left join the pref values table twice, but use the WHERE to limit it to only prefs of type 20 or 21. This works. However, I’m not sure it is the best way to do such a query… how would you recommend doing this query?
This is much more efficient than your query.