我有这张图表
我想做的是得到这个输出:
你是如何设法完成这个查询的?
我有这个代码
SELECT users.firstname, users.lastname,
users.screenname, posts.post_id, posts.user_id,
posts.post, posts.upload_name,
posts.post_type, posts.date_posted
FROM website.users users
INNER JOIN website.posts posts ON (users.user_id = posts.user_id)
ORDER BY posts.pid DESC
//PROBLEM with this one is that it only views the post from all users.
//SO I added
SELECT COUNT(user_id) AS friends, SUM(user_id = ?) AS you, user_id
FROM feeds WHERE post_id = ?
//This one will give you two fields containing how many different users **feeds** the
post
请大家帮忙。其实这个我只是关注Facebook的“LIKE”状态 唯一的问题是我不是这类东西的业余爱好者,所以我很高兴听到您的所有回答。我真的需要你的帮助
最佳答案
如果我没理解错的话,您需要与 feeds
表进行外部连接(以便保留所有 posts
,即使没有关联的 feeds
),然后 GROUP BY post.pid
以便将每个帖子的所有此类 feeds 合并在一起,然后 SELECT
所需的信息。
我使用 MySQL 的 GROUP_CONCAT()
函数获取所有用户的逗号分隔列表(最多 group_concat_max_len
)
给定帖子的“提要”(如果需要,您可以使用 SEPARATOR
修饰符更改分隔符)。
SELECT users.firstname, users.lastname,
users.screenname, posts.post_id, posts.user_id,
posts.post, posts.upload_name,
posts.post_type, posts.date_posted,
COUNT(feeds.user_id) AS friends, -- number of "likes"
SUM(feeds.user_id = ?) AS you, -- did I like this?
GROUP_CONCAT(feeds.user_id) -- who likes it?
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)
GROUP BY posts.pid
ORDER BY posts.pid DESC
更新
要获取“喜欢”帖子的用户的全名,不包括自己,需要第二次加入users
表:
SELECT users.firstname, users.lastname,
users.screenname, posts.post_id, posts.user_id,
posts.post, posts.upload_name,
posts.post_type, posts.date_posted,
COUNT(feeds.user_id) AS friends, -- number of "likes"
SUM(feeds.user_id = ?) AS you, -- did I like this?
GROUP_CONCAT(
CASE WHEN NOT likes.user_id = ? THEN -- exclude self
CONCAT_WS(' ', likes.firstname, likes.lastname) -- full names
END
)
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
关于PHP mysql如何关联三个表显示不同表的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10430966/