我有2个表 User1 和 Relationship ,这是某种用户-朋友关系。我需要找到一个用户的所有朋友。
例如:我有一个ID=3
用户,并且我需要查找与此用户拥有Relationship.STATUS = 1
的所有用户。
仅供参考,我是SQL的初学者,所以我知道这是一个非常简单的任务,但我无法处理。
我尝试使用JOIN,但未成功。
SELECT *
FROM USER1
RIGHT JOIN RELATIONSHIP R on USER1.USER1_ID = R.USER_ID_FROM OR USER1.USER1_ID = R.USER_ID_TO
WHERE R.USER_ID_FROM = :id
OR R.USER_ID_TO = :id AND R.STATUS = :status AND USER1_ID != :id;
我的桌子:
TABLE USER1
(
USER1_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)
);
TABLE RELATIONSHIP
(
USER_ID_FROM NUMBER NOT NULL,
USER_ID_TO NUMBER NOT NULL,
STATUS SMALLINT DEFAULT 0,
CONSTRAINT FK_USER_ONE FOREIGN KEY (USER_ID_FROM) REFERENCES USER1 (USER1_ID),
CONSTRAINT FK_USER_TWO FOREIGN KEY (USER_ID_TO) REFERENCES USER1 (USER1_ID),
CONSTRAINT PK_RELATIONSHIP PRIMARY KEY (USER_ID_FROM, USER_ID_TO)
);
答案 0 :(得分:0)
哼哼不确定,但我会尝试这样的事情:
SELECT u.* FROM USER1 u LEFT JOIN RELATIONSHIP r ON r.USER_ID_FROM = :id AND r.STATUS = 1 AND u.USER1_ID = r.USER_ID_TO;
其中的id是您要查找朋友的用户的ID。
答案 1 :(得分:0)
SELECT *
FROM USER1 U
LEFT JOIN RELATIONSHIP R ON R.USER_ID_FROM = U.ID AND R.[STATUS] = 1
LEFT JOIN USER1 F ON R.[USER_ID_TO] = F.[ID]
WHERE U.[Id] = your_id
然后仅过滤用户。使用左联接是因为用户可能没有任何朋友。而且我知道您想找到该用户以及该用户的任何朋友。
答案 2 :(得分:0)
尝试一下:
(SELECT *
FROM USER1 u
LEFT JOIN RELATIONSHIP f ON u.USER1_ID = f.USER_ID_FROM
WHERE f.USER_ID_TO= 3 AND f.STATUS = 1)
union
(SELECT *
FROM USER1 o
LEFT JOIN RELATIONSHIP t ON o.USER1_ID = t.USER_ID_TO
WHERE t.USER_ID_FROM= 3 AND t.STATUS = 1)
答案 3 :(得分:0)
如果您只想要ID,则可以使用条件逻辑来选择哪个用户ID:
select (case when user_id_from = 1 then user_id_to else user_id_from
end) as other_user_id
from relationship r
where 1 in (user_id_from, user_id_to) and
status = 3;
如果您实际上需要所有用户信息,我建议您使用exists
:
select u.*
from user1 u
where exists (select 1
from relationship r
where r.status = 3 and
( (r.user_id_from = 1 and r.user_id_to = u.id) or
(r.user_id_to = 1 and r.user_id_from = u.id)
)
);