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

前端 未结 4 1985
深忆病人
深忆病人 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:39

    Create a User table then a Relationships table where you store the id of the two friend and any kind of information about their relationship.

    SQL diagram

    SQL diagram

    MySQL code

    CREATE TABLE `Users` (
      `id` TINYINT NOT NULL AUTO_INCREMENT DEFAULT NULL,
      PRIMARY KEY (`id`)
    );
    
    CREATE TABLE `Relationships` (
      `id` TINYINT NOT NULL AUTO_INCREMENT DEFAULT NULL,
      `userid` TINYINT NULL DEFAULT NULL,
      `friendid` TINYINT NULL DEFAULT NULL,
      `friended` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`)
    );
    
    ALTER TABLE `Relationships` ADD FOREIGN KEY (userid) REFERENCES `Users` (`id`);
    ALTER TABLE `Relationships` ADD FOREIGN KEY (friendid) REFERENCES `Users` (`id`);
    

    SQL selection

    After you fill up the tables with data, you can create your SQL SELECT query to get all of your friends. Your friends are those whose id is in one side side while your id is in the other side. You check both sides for your id so you don't need to store relationships twice. Also you have to exclude your id, because you can't be your own friend (in a normal, healthy world).

    SELECT *
    FROM Users u
       INNER JOIN Relationships r ON u.id = r.userid
       INNER JOIN Relationships r ON u.id = r.friendid
    WHERE
       (r.userid = $myid OR r.friendid = $myid)
       AND r.friended >= $startdate
       AND r.friended <= $enddate
       AND u.id != $myid;
    

    Where $myid, $startdate and $enddate can be PHP variables so in double quotes you can pass this code directly to your database.

提交回复
热议问题