I have two database tables: one with user IDs and one containing user metadata (with multiple rows related to the same user ID).
users
table structure example
id | USERNAME |
---|---|
1 | user 1 |
2 | user 2 |
3 | user 3 |
users_meta
data structure example
meta_id | user_id | meta_key | meta_val |
---|---|---|---|
1 | 1 | key1 | a |
2 | 1 | key2 | b |
3 | 2 | key1 | d |
4 | 3 | key1 | e |
5 | 3 | key2 | f |
I’d like query whether a user has got a metadata database row.
SELECT * FROM users
LEFT OUTER JOIN users_meta ON users.id = users_meta.user_id
WHERE users_meta.meta_key != "key2"
GROUP BY id
ORDER BY id ASC
LIMIT 0, 100
How do I query to get the user id 2
not having a meta value related to key2
?
2
Answers
Thanks @Kukuh Gumilang for your reply, it put me somehow on the right track to code a shorter and better solution, perfectly adapting to my complex framework.
The solution was literally as simple as adding a new join and a condition
Try this. I use sub queries, union, and query from query.