Friday, March 9, 2012

help with query

I have a table UserData which amongst others contains a field UserCode (int) and Name and Country.

I also have a table UsersAndSports which contains a field UserCode and a field SportID (both int).
This table can have multiple rows for the same usercode:
UserCode SportID
12 7
12 9
12 4
15 9
15 8

I want a user on my site to search for users with an interest for the same sports (say SportID 7 OR 9).
In this case that would return UserCode 12 two times and UserCode 15 once. I just need the matching UserCode once.

I want to have a query that returns the UserCode, Name, Country AND the SportID.
What would that query be?

I tried something like this (which doesnt work ofcourse :) ):

SELECT tblUserData.UserName,UserCode,Country FROM aspnet_Users
INNER JOIN tblUserData ON aspnet_Users.UserId = tblUserData.UserID
INNER JOIN tblUserData ON tblUserData.UserCode IN (SELECT DISTINCT UserCode FROM tblUsersAndSports WHERE SportID=7 OR SportID=9)
WHERE tblUserData.Username<>''

I don't really understand. You say:

I want to have a query that returns the UserCode, Name, Country AND the SportID


But you also only want to return one user? But if a user has more than one SportID than which SportID should it be returning?|||Excuse me..I just want to return a user which has sportid x or y. I dont need to retreive the sportid's.

So when a user searches for other users who have sportid 7 OR 9, and user 1843 has sportID 7 and 9, then just usercode 1843 is returned.

I hope this clarifies my problem?|||OK, I think I understand now. In that case you can just do this:

SELECT DISTINCT UserData.UserCode
FROM UserData INNER JOIN
UsersAndSports ON UserData.UserCode = UsersAndSports.UserCode
WHERE (SportID = 7 OR SportID = 9)|||now I see it it's actually quite easy...:)
Thanks!

No comments:

Post a Comment