Lets say I have a variable ‘userid’, I want to select from aspnet_Membership AND aspnet_AccountProfile tables. They both have the column userid, I just want to be able to make a statement like SELECT * FROM aspnet_AccountProfile, aspnet_Membership WHERE UserId=@UserId and it gets the records with the matching user id for BOTH tables. how do I do this? Thank you!
Share
That is called a
JOIN:There are several basic types of join based on what data exactly you want. These are related to set theory/relational algebra. I’ll list the most common ones:
INNER JOIN
Use this when you want to return every possible combination of rows where both tables have a matching UserId. Some rows in either table may not get returned in an inner join.
Another way of writing an INNER JOIN (Which I wouldn’t encourage if you want to understand joins) is:
Of course, to select the specific UserId you want, you add a condition on either table eg:
AND aspnet_AccountProfile.UserId = @UserId
OR
AND aspnet_Membership.UserId = @UserId
Either of those two will work fine for an inner join.
LEFT OUTER JOIN
Use this when you want to return all rows from the first table in your query, and every combination where the UserId in the second table matches the first. Some rows in the second table (Membership, in this case) may not get returned at all.
You have to use the left column to narrow down your criteria in this case, or it will automatically get converted to an INNER JOIN.
WHERE aspnet_AccountProfile.UserId = @UserId
RIGHT OUTER JOIN
This is fairly uncommon, because it can usually be written as a LEFT outer join. It’s like a left outer join, but all rows from the second table in the relation are returned instead of the first.
FULL OUTER JOIN
Use this if you need to relate all the rows with a matching UserId in AccountProfile to the corresponding rows in Membership, but also need to know which rows in either table don’t have a match in the other one.
Getting results for only a single user is a little trickier in a FULL OUTER JOIN. You have to specify that a NULL or the correct value is okay in either table.