mysql相关字段 [英] mysql related fields

查看:40
本文介绍了mysql相关字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这4个字段是相互关联的

These 4 fields are related to each other

我希望它输出为:

在我的查询中:

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的所有帖子以及来自当前登录用户的帖子.如果好友表上没有匹配的朋友,则只输出所有来自用户的帖子.请伙计们,我需要你们的帮助.

Now, I am having a problem on which part should I join the friends table, I want to display all the posts from friend_id or user_id and also the post from user who is currently logged in. If no friend matched on the friend table, then just output all the posts from user. Please guys I need your help.

friends.friend_id = 当前用户的好友

friends.friend_id = friend of the current user

friends.user_id = 用户的当前好友

friends.user_id = current friend of the user

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

Thus, friends.friend_id = posts.user_id or friends.user_id = posts.user_id

如果我的朋友表有不明白的地方,请帮我改一下,让它更好.

If my friends table is not understandable, please help me change it to make it better.

推荐答案

您希望看到来自用户或其朋友的帖子.因此,与其加入用户,不如加入子查询,如下所示:

You would like to see posts either from the user, or from his friends. Therefore, instead of joining with users, join with the subquery, like this:

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;

测试输出此处.

这篇关于mysql相关字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆