How to make SQL many-to-many same-type relationship table

前端 未结 4 1991
深忆病人
深忆病人 2020-11-27 17:19

I\'m a newbie to SQL and I\'m jumping in head first trying to learn as much as possible as I\'m coding, which is difficult as I\'m designing the database I\'ll have to live

4条回答
  •  囚心锁ツ
    2020-11-27 17:29

    A single linking table suffices, like so:

    People( PersonId bigint, Name nvarchar, etc )
    Friends( FromPersonId bigint, ToPersonId bigint, DateAdded datetime )
    

    Example queries:

    Who is friends with me? (i.e. people who have added me as a friend, but not necessarily reciprocated)

    SELECT
        People.Name
    FROM
        Friends
        INNER JOIN People ON Friends.FromPersonId = People.PersonId
    WHERE
        Friends.ToPersonId = @myPersonId
    

    Who added me between two dates?

    SELECT
        People.Name
    FROM
        Friends
        INNER JOIN People ON Friends.FromPersonId = People.PersonId
    WHERE
        Friends.ToPersonId = @myPersonId
        AND
        Friends.DateAdded >= @startDate
        AND
        Friends.DateAdded <= @endDate
    

提交回复
热议问题