这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
如果我的朋友表不可理解,请帮助我改变它以使其更好。
答案 0 :(得分:2)
如果我很好理解你想基于friends = user_id加入好友表,如果不匹配好友表的user_id上的JOIN,那么你可以尝试这样的事情:
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 friends, 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)
LEFT JOIN website.friends friends ON ((posts.user_id = friends.user_id) OR (posts.user_id = friends.friends_id) )
GROUP BY posts.pid
ORDER BY posts.pid DESC
我基本上在好友表中添加了一个JOIN,并在你想要加入的两个字段上添加了一个OR ...
答案 1 :(得分:2)
您希望查看来自用户或其朋友的帖子。因此,不要加入用户,而是加入子查询,如下所示:
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。