Jump to content

Archived

This topic is now archived and is closed to further replies.

drifter

two table query - just point me in the right direction

Recommended Posts

OK - I have a table with users...

userid - name - etc - etc
1 - scott
2 - angela
3 - perte
4 - jamie

I have a secong table with hobbies...

id - userid - hobby
1 - 1 - golf
2 - 1 - swimming
3 - 2 - golf
4 - 4 - tennis
5 - 1 - bowling

I want to find all users that have a hobby of golf and swimming.

How do I do this?

Really I just need to get pointed in the right direction.

Thanks in advance
Scott

Share this post


Link to post
Share on other sites
[code]
SELECT u.name
FROM users u
LEFT JOIN hobbies h
ON u.userid = h.userid
WHERE h.hobby = 'golf' OR h.hobby = 'swimming'
GROUP BY u.name
HAVING COUNT(*) = 2
[/code]

Share this post


Link to post
Share on other sites
Or:

[code]
SELECT u.name, COUNT(h.userid) AS cnt
FROM users u
LEFT JOIN hobbies h
ON u.userid = h.userid
WHERE h.hobby = 'golf' OR h.hobby = 'swimming'
GROUP BY u.name
HAVING cnt = 2
[/code]

Note that if you use LEFT JOIN, then technically you should be counting the non-null records in the "right" table, but it's irrelevant in this particular case since you're testing an equality.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.