I have a USERS table like this
USERS
user_id | username
1 tom
2 sam
I also have a USER_META table like this
USER_META
user_meta_id | user_id | meta_key | meta_value
1 1 active 1
2 1 car dodge
3 2 active 0
4 2 car honda
My problem is that I need to select the meta_keys active and and car but only for users who have a value of 1 for active so my result set should be something like this
user_id | user_name | user_meta_id | meta_key | meta_value
1 tom 1 active 1
1 tom 2 car dodge
I have tried a few things but I cannot get this type of result set. Here is what I thought might work
SELECT * FROM USERS
LEFT JOIN USER_META
ON USERS."user_id" = USER_META
AND (USER_META."meta_key" = 'active' OR USER_META."meta_key" = 'car')
WHERE (USER_META."meta_key" = 'active'
AND USER_META."meta_value" = 1)
the problem with this is that I get a result set that is missing the car meta_key/meta_value
user_id | user_name | user_meta_id | meta_key | meta_value
1 tom 1 active 1
How can I modify the query to get all of the meta information? thanks.
First off, this sort of entity-attribute-value data model is generally a very poor idea. You’re basically re-implementing what a relational database gives you out of the box and queries get very unwieldy very quickly. Generally, you’ll need to join in the
USER_METAtable N times in order to either get N attributes as columns or in order to have N predicates on your data.On the data modeling front, future developers will generally be grateful if you avoid creating case-sensitive column names so that they don’t have to double-quote every identifier every time.
Since you need two keys, you should be able to do something like this (I assume that
meta_valueis always stored as a character string even if it represents a numeric or boolean value)which returns the expected results for the data you posted