I have users table
ID NAME
1 John
2 Mike
3 Jack
and table with attributes and user IDs
USER ATTRIBUTE
1 1
1 2
2 4
I need to select all users with attribute 1 AND 2 (so, in this example user #1 John). Attributes can be more than two.
I'v tried
SELECT * FROM user u LEFT JOIN attributes a ON u.id = a.user
WHERE a.attribute = 1 AND a.attribute = 2
but of course it not working..
having clause can be used with sum
You'll need a group by .... having
You are looking for all users for whom EXIST attribute 1 and 2. One way to solve this - as the name suggests - is the EXISTS clause:
Another way is this: Find all user ids that have both attributes, then select from users table.
In case there are duplicate entries in attributes, you would have to replace
count(*)
withcount(distinct attribute)
.There are other ways to approach this. I think these two mentioned are rather straight-forward.
You will need to use a combination of
IN()
andGROUP BY ... HAVING
to achieve this. Also no need for a join if all you need is user ID's. So something like:If you need user id's and names you can simply join this record set derived from the query above as a filter to the users table: