gpt4 book ai didi

php - mysql相关领域

转载 作者:可可西里 更新时间:2023-11-01 08:07:04 25 4
gpt4 key购买 nike

这4个字段是相互关联的

Friends - posts - users - feeds

我希望它输出为:enter image description here

在我的查询中:

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 表的哪一部分, 我想显示来自friend_id 或user_id 的所有帖子 以及来自当前登录用户的帖子。如果 friend 表 上没有匹配的 friend ,则只输出所有来自用户的帖子。伙计们,我需要你们的帮助。

friends.friend_id = 当前用户的好友

friends.user_id = 用户的当前好友

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

如果我的friends表看不懂,请帮我修改一下,让它变得更好。

最佳答案

您想查看来自用户或其 friend 的帖子。因此,不是与用户连接,而是与子查询连接,如下所示:

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 .

关于php - mysql相关领域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10570154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com