我有这个图
我想做的是输出:
你如何设法查询这个?
我有这段代码
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”状态 唯一的问题是我不是这种东西的业余爱好者,所以我很高兴听到你的所有答案。我真的需要你的帮助
答案 0 :(得分:3)
如果我理解正确,你想要一个带有feeds
表的外联接(为了保留所有posts
,即使没有关联的feeds
),那么{ {1}}为每个帖子合并所有此类Feed,并GROUP BY post.pid
所需信息。
我使用MySQL的GROUP_CONCAT()
函数来获取所有用户(最多group_concat_max_len
)的逗号分隔列表
给定帖子的“提要”(如果需要,您可以使用SELECT
修饰符更改分隔符。)
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
答案 1 :(得分:2)
如果您想为所有用户执行此操作并同时获取Feed,则必须加入此feed
表:
SELECT u.firstname, u.lastname,
u.screenname, p.post_id, p.user_id,
p.post, p.upload_name,
p.post_type, p.date_posted,
COUNT(f.user_id) AS friends, SUM(f.user_id = ?) AS you
FROM website.users u
INNER JOIN website.posts p ON (u.user_id = p.user_id)
LEFT JOIN website.feeds f ON (p.post_id = f.post_id)
GROUP BY p.pid
ORDER BY p.pid DESC
这个应该可以解决这个问题......