SQL/Oracle - 将用户 ID 添加到朋友 table,名称为 FriendID

SQL/Oracle - adding a userID to a friend table with the name FriendID

我目前正在使用 Oracle APEX with Objects 为高级数据库大学模块开发一个 corusework。 我们需要用一个用户 table 和一个朋友 table 创建一个类似 facebook 的应用程序。 用户 table 创建如下:

CREATE TABLE user_table (
    userId NUMBER NOT NULL, 
    userName VARCHAR2(50) NOT NULL, 
    emailAddress     VARCHAR2(150) NOT NULL, 
    password VARCHAR(20) NOT NULL, PRIMARY KEY(userId)
);

关注table的朋友:

CREATE TABLE friends_following_table(
    friendId NUMBER NOT NULL,
    userId NUMBER references user_table,
    PRIMARY KEY(friend_id )
);

我的问题: 我需要 friends 连接到用户。 userId怎么会变成friendId?还是完全错了?

Sample user: 
userId: 1 
name: shannon
userId: 2
name: Alison 

用户 1 和用户 2 需要成为朋友,数据库需要反映这一点

谢谢

试试这个模式:

CREATE TABLE UserTable (
  UserID NUMBER NOT NULL
  , UserName VARCHAR2(50) NOT NULL
  , EmailAddress VARCHAR2(150) NOT NULL
  , Password VARCHAR(20) NOT NULL
  , CONSTRAINT PK_UserTable PRIMARY KEY(UserID)
);

CREATE TABLE FriendTable (
  UserID NUMBER NOT NULL
  , FriendID NUMBER NOT NULL
  , CONSTRAINT PK_FriendTable PRIMARY KEY(UserID, FriendID)
  , CONSTRAINT FK_FriendTable_UserID FOREIGN KEY (UserID) REFERENCES UserTable(UserID)
  , CONSTRAINT FK_FriendTable_FriendID FOREIGN KEY (FriendID) REFERENCES UserTable(UserID)
);

根据您问题中给出的 user_table

CREATE TABLE user_table (
userId NUMBER NOT NULL, 
userName VARCHAR2(50) NOT NULL, 
emailAddress     VARCHAR2(150) NOT NULL, 
password VARCHAR(20) NOT NULL, PRIMARY KEY(userId)
);

并且还基于您的示例数据和所需的输出:

Sample user: userId: 1 name: shannon userId: 2 name: Alison

User 1 and user 2 need to be friends and the database needs to reflect this

事实上,用户之间存在 Many-To-Many 关系,因此您需要这样的 table 关系:

CREATE TABLE friends_following_table(
user_id NUMBER REFERENCES user_table,
follower_id NUMBER REFERENCES user_table,
PRIMARY KEY(user_id,follower_id)
);

对于您的示例数据:

INSERT INTO user_table 
VALUES(1,'shannon','s@so.com','123');
INSERT INTO user_table 
VALUES(2,'Alison','a@so.com','123');

现在您必须指定哪个在另一个之后:

如果 user 2 跟随 user 1:

INSERT INTO friends_following_table VALUES(1,2);

如果 user 1 跟随 user 2:

INSERT INTO friends_following_table VALUES(2,1);

您可以通过简单的 join:

提取 every two followers
SELECT u1.userId,u1.userName,
       u2.userName "FOLLOWS"
FROM user_table u1
JOIN friends_following_table f on u1.userId=f.follower_id
JOIN user_table u2 on u2.userId=f.user_Id

您可以使用 count 函数和 left join 计算每个用户的 关注者数量 :

SELECT u.userId,u.userName,
       count(f.follower_id) "FOLLOWERS"
FROM user_table u
LEFT JOIN friends_following_table f on u.userId=f.user_Id
GROUP BY u.userId,u.userName

您还可以使用 count 函数和 left join:

SELECT u.userId,u.userName,
       count(f.follower_id) "FOLLOWINGS"
FROM user_table u
LEFT JOIN friends_following_table f on u.userId=f.follower_id
GROUP BY u.userId,u.userName