[英]setting content to be viewable by friends only
Say I have a table that holds content: 假设我有一个包含内容的表:
Content(contentID, title, body, privacyType) 内容(contentID,title,body,privacyType)
Privacy type can be: 隐私类型可以是:
Public = 1 (anyone can view it) Private = 2 (only the author can view it) Friends = 3 (only friends can view it) Public = 1(任何人都可以查看)Private = 2(只有作者可以查看)Friends = 3(只有朋友可以查看)
I have a users table: 我有一个用户表:
Users(userID, username) 用户(userID,用户名)
THen I have a mapping table for the users friends: 我有一个用户朋友的映射表:
Friends (userID, friendID) 好友(userID,friendID)
Now when I am listing all the content, it should list content that is either public OR I am a friend of that user (for a logged in user) 现在,当我列出所有内容时, 它应该列出公共内容或我是该用户的朋友 (对于登录用户)
How would I do a query for this? 我该如何查询?
You didn't provide the field where the content authorship is stored, so I'll assume it's content.author
: 您没有提供存储内容作者的字段,因此我假设它是
content.author
:
SELECT *
FROM content
WHERE public = 1
OR
(
public = 3
AND EXISTS
(
SELECT NULL
FROM friends
WHERE userId = @me
AND friendID = content.author
)
)
, or better this: 或者更好的这个:
SELECT *
FROM content
WHERE public = 1
UNION ALL
SELECT *
FROM content
WHERE public = 3
AND EXISTS
(
SELECT NULL
FROM friends
WHERE userId = @me
AND friendID = content.author
)
, if your author
field is selective and sorting is cheaper than filtering. ,如果您的
author
字段是选择性的,并且排序比过滤便宜。
Also note that if your friendship is a symmetrical relation (ie if a userA
is a friend to userB
, then userB
is a friend to userA
), it's better stored in a table like this: 还要注意的是,如果你的友谊是一个对称的关系(即如果
userA
是一个朋友给userB
,然后userB
是朋友userA
),它是在一个表像这样更好地存储:
userA userB
with a check constraint: 带有检查约束:
userA < user B
Yuo always put the user with least id
first. Yuo总是把用户放在
id
最少的位置。
In this case, your query like this: 在这种情况下,您的查询如下:
SELECT *
FROM content
WHERE public = 1
UNION ALL
SELECT *
FROM content
WHERE public = 3
AND EXISTS
(
SELECT NULL
FROM friends
WHERE userA = @me
AND userB = content.author
UNION ALL
SELECT NULL
FROM friends
WHERE userB = @me
AND userA = content.author
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.