简体   繁体   中英

Nested MySQL query for multiple privacy check

I have 1 table post with userid , posttypeid , privacy and originalpostid

Privacy can be 1 (Everyone),2 (Friends),3 (Friends & Followers),4 (Only Me)

User can share any user post but people who visits their wall can see post according to privacy between userid of original post and currentuser

I also have function which returns relation between user and user2 but in this case with mysql single query how can I handle conditionally.

For example query returning 10 result and 4 of them are shared post now I've to check each post that if user privacy is 1 then it should be visible to all if 2 then visible to originalpostowner friend only like that

I have figure out some condition like

IF(originalpostid!=0,(privacy=1,true,(privacy=2,(ORIGINAL_POST_QUERY & then check if SUBQUERY_TO_RETURN_IF_USER_IS_FRIEND_OR_NOT),(privacy=3,(ORIGINAL_POST_QUERY & then check if SUBQUERY_TO_RETURN_IF_USER_IS_FRIEND_OR_FOLLOWER),(privacy=4,(ORIGINAL_POST_QUERY & then check if CHECK_IF_CURRENTUSER_AND_ORIGINALPOSTID_USERID_IS_SAME),true)))),true)

This one is bit messy and also in this case I have to run subquery all times for originalpost details to compare user id is there any easy solution for it ?

If I understand correctly, a query like this would do it:-

SELECT Post.PostID 
FROM Post 
WHERE Post.StatusID=2 
AND Post.privacy = 1
UNION
SELECT Post.PostID 
FROM Post 
INNER JOIN relationship
ON Post.userid = relationship.userid
WHERE Post.StatusID=2 
AND relationship.status = 2
AND relationship.userid_other = $CurrentUser
AND Post.privacy = 2
UNION 
SELECT Post.PostID 
FROM Post 
INNER JOIN relationship
ON Post.userid = relationship.userid
WHERE Post.StatusID=2 
AND relationship.status = 1
AND relationship.userid_other = $CurrentUser
AND Post.privacy = 3
UNION 
SELECT Post.PostID 
FROM Post 
WHERE Post.StatusID=2 
AND Post.userid = $CurrentUser

assuming a table of relationships like this:-

CREATE TABLE relationship
(
    userid  INT,
    userid_other    INT,
    status  INT
);

status = 1 for follower, 2 for friend

This is 4 unioned queries (union will exclude duplicates). The query first gets posts which are for everyone, the 2nd posts that are for friends where the current user is a friend of the poster, the 3rd gets posts which are for followers where the current user is a follower of the poster and the 4th gets posts which are open for anyone to read.

But to give anything better I would need to know how your relationships are stored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM