We have many-to-many Relationship and these are the details for the same and its non-hierarchical data.
For a User name test 1 >> find Team >> And the find others Members of the Team
Table Team (Team Table)
Id Name
1 Ninja
2 Maverick
3 Transformer
Table User (User Table)
Id Name Email
1 test1 test1@test.com
2 test2 test2@test.com
3 test3 test3@test.com
Table Team_USER_Map (User Map)
ID User_Id Team ID
1 1 1
2 1 2
3 2 3
4 2 1
5 3 1
6 3 2
7 3 3
Problem Statement :
Depending upon the User Name, I need to find all other's user for same Team.
So for user name = 'test1', I need to find the Team its belongs and other user belonging to same team.
Try this:
DECLARE @Name as nvarchar (50)
SET @Name = 'test1'
SELECT u.Name as UserName, u.Email, t.Name as TeamName
FROM Team as t INNER JOIN Team_USER_Map as tum ON t.Id = tum.Team_ID
INNER JOIN User as u ON u.Id = tum.User_Id
WHERE u.Name LIKE @Name OR tum.Team_ID =
(
SELECT t.Id
FROM Team as t INNER JOIN Team_USER_Map as tum ON t.Id = tum.Team_ID
INNER JOIN User as u ON u.Id = tum.User_Id
WHERE u.Name LIKE @Name
)
I think that is what you want to achieve. The first part of WHERE
clause is easy because it returns the user with it's name.
In second part, you must use SELECT WITHIN SELECT statement to get all users which belong to team of user of typed name.
I hope it's helpful and clear enough.
Good luck!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.