我已经建立了一个数据库结构,用户可以像在facebook上一样在他们之间建立“朋友联系”。
每个用户都可以将文本保存到tbl_Statuses
表,只有他们的朋友才能看到此消息
但是我遇到了SQL问题:(
tbl_Friends{UserId, FriendId, Accepted}
tbl_Statuses{StatusId, Text, UserId}
我正试图获得状态:
- 我写的
- 我的朋友写的
我尝试了一些东西,但我无法想象:(
select s.*
from tbl_Statuses s left join tbl_Friends f on s.userId = f.UserId
where s.userId = f.UserId
答案 0 :(得分:2)
SELECT *
FROM tbl_Statuses
WHERE UserId = @MyUserId
OR UserId IN (SELECT FriendId FROM tbl_Friends WHERE UserId = @MyUserId AND Accepted = 1)
答案 1 :(得分:0)
-- What you say
SELECT *
FROM tbl_StatuseS
WHERE UserId = @userId
union
-- What your friends say
SELECT s.*
FROM tbl_Friends f
join tbl_Statuses s on s.userId = f.FriendId
WHERE f.UserId = @userId
and f.Accepted = 1