PHP-MySQL相关领域

提问

这4个字段相互关联

我希望它输出为:

在我的查询中:

SELECT users.firstname, users.lastname, users.screenname, posts.post_id, posts.user_id,
posts.post, posts.upload_name, posts.post_type, 
DATE_FORMAT(posts.date_posted, '%M %d, %Y %r') AS date, 
COUNT(NULLIF(feeds.user_id, ?)) AS everybody, SUM(feeds.user_id = ?) AS you,
GROUP_CONCAT(CASE WHEN NOT likes.user_id = ? THEN 
             CONCAT_WS(' ', likes.firstname, likes.lastname)
                    END
            ) as names
FROM website.users users
INNER JOIN website.posts posts ON (users.user_id = posts.user_id)
LEFT  JOIN website.feeds feeds ON (posts.post_id = feeds.post_id)
LEFT  JOIN website.users likes ON (feeds.user_id = likes.user_id)
GROUP BY posts.pid
ORDER BY posts.pid DESC

现在,我在加入朋友表的哪个部分上遇到问题,
  我想显示来自friend_id或user_id的所有帖子,以及来自当前登录用户的帖子.如果在好友表上没有匹配的朋友,则仅输出该用户的所有帖子.拜托,我需要你的帮助.

friends.friend_id =当前用户的朋友

friends.user_id =用户的当前朋友

因此,friends.friend_id = posts.user_id或friends.user_id = posts.user_id

如果我的friends表无法理解,请帮助我对其进行更改以使其更好.

最佳答案

您想查看来自用户或其朋友的帖子.因此,不要与用户一起加入,而是与子查询一起加入,如下所示:

SELECT users.firstname, users.lastname, users.screenname,
       posts.post_id, posts.user_id, posts.post, posts.upload_name,
       posts.post_type, DATE_FORMAT(posts.date_posted, '%M %d, %Y %r') AS date, 
       COUNT(NULLIF(feeds.user_id, ?)) AS everybody,
       SUM(feeds.user_id = ?) AS you,
       GROUP_CONCAT(CASE WHEN NOT likes.user_id = ? THEN 
             CONCAT_WS(' ', likes.firstname, likes.lastname) END) as names
  FROM (SELECT user_id FROM website.users WHERE user_id = ?
        UNION ALL
        SELECT user_id FROM website.friends WHERE friend_id = ?
        UNION ALL
        SELECT friend_id FROM website.friends WHERE user_id = ?) AS who
  JOIN website.users users ON users.user_id = who.user_id
  JOIN website.posts posts ON users.user_id = posts.user_id
  LEFT  JOIN website.feeds feeds ON posts.post_id = feeds.post_id
  LEFT  JOIN website.users likes ON feeds.user_id = likes.user_i)
 GROUP BY posts.pid
 ORDER BY posts.pid DESC;

测试输出here.

评论