SQL如何选择所有用户和用户的好友帖子

时间:2019-06-30 06:36:10

标签: sql

我需要查找所有用户和用户的好友帖子。例如:我有一个ID = 0的用户。该用户有3个ID为1,2,3的朋友(状态=已接受)。我需要使用一个SQL查询选择所有USER_POSTED = 0、1、2、3的帖子。

问题是-用户可以拥有从零到无限的朋友。我可以找到所有用户朋友的ID:

SELECT U.USER_ID
FROM USERS U
         JOIN RELATIONSHIP R
              ON (U.USER_ID = R.USER_ID_FROM OR U.USER_ID = R.USER_ID_TO)
                  AND U.USER_ID != :userId
WHERE R.STATUS = :status
  AND (R.USER_ID_TO = :userId OR R.USER_ID_FROM = :userId);

但是我不知道如何在一个查询中找到他们所有的帖子。

SQL数据模型:

CREATE TABLE USERS
(
    USER_ID      NUMBER PRIMARY KEY,
    USER_NAME    NVARCHAR2(64),
    REAL_NAME    NVARCHAR2(64),
    EMAIL        NVARCHAR2(64),
    PHONE_NUMBER NVARCHAR2(64),
    BIRTH_DATE   TIMESTAMP,
    POST_ID      NUMBER,
    PASSWORD     NVARCHAR2(16)

);

CREATE TABLE POST
(
    POST_ID          NUMBER PRIMARY KEY,
    MESSAGE          NVARCHAR2(128),
    DATE_POSTED      TIMESTAMP,
    LOCATION         NVARCHAR2(128),
    USERS_TAGGED     NUMBER,
    USER_POSTED      NUMBER,
    USER_PAGE_POSTED NUMBER,
    CONSTRAINT USER_TARGET_FK FOREIGN KEY (USERS_TAGGED) REFERENCES USERS (USER_ID),
    CONSTRAINT USER_POSTED_FK FOREIGN KEY (USER_POSTED) REFERENCES USERS (USER_ID),
    CONSTRAINT USER_PAGE_POSTED_FK FOREIGN KEY (USER_PAGE_POSTED) REFERENCES USERS (USER_ID)
);

ALTER TABLE USERS
    ADD CONSTRAINT POST_FK FOREIGN KEY (POST_ID) REFERENCES POST (POST_ID);

CREATE TABLE RELATIONSHIP
(
    USER_ID_FROM         NUMBER NOT NULL,
    USER_ID_TO           NUMBER NOT NULL,
    STATUS               NVARCHAR2(256),
    FRIENDS_REQUEST_DATE TIMESTAMP,
    CONSTRAINT FK_USER_ONE FOREIGN KEY (USER_ID_FROM) REFERENCES USERS (USER_ID),
    CONSTRAINT FK_USER_TWO FOREIGN KEY (USER_ID_TO) REFERENCES USERS (USER_ID),
    CONSTRAINT PK_RELATIONSHIP PRIMARY KEY (USER_ID_FROM, USER_ID_TO)

);

1 个答案:

答案 0 :(得分:1)

显示帖子的逻辑是,该帖子需要由某些:userId或同一用户的直接朋友来创作。

SELECT p.POST_ID, p.MESSAGE
FROM POST p
WHERE
    p.USER_POSTED = :userId OR
    p.USER_POSTED IN (SELECT USER_ID_FROM FROM RELATIONSHIP
                      WHERE USER_ID_TO = :userId
                      UNION ALL
                      SELECT USER_ID_TO FROM RELATIONSHIP
                      WHERE USER_ID_FROM = :userId);

请注意,我在假定朋友关系可以在任何方向上使用联合。如果您总是将关系存储在一个方向上(例如,从最小到最大),那么联合是多余的。