简体   繁体   English

与多对多关系的sql查询

[英]sql query with many to many relationship

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 对于用户名测试1 >>查找团队>>然后查找其他团队成员

 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. 因此,对于用户名='test1',我需要找到它所属的团队以及属于同一团队的其他用户。

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. WHERE子句的第一部分很容易,因为它以其名称返回用户。

In second part, you must use SELECT WITHIN SELECT statement to get all users which belong to team of user of typed name. 在第二部分中,您必须使用SELECT WITHIN SELECT语句来获取属于类型名称用户组的所有用户。

I hope it's helpful and clear enough. 我希望它会有所帮助并且足够清楚。

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM