5

我有这张图发布提要

我想做的是有这个输出: 喜欢帖子 - 喜欢 Facebook

你是如何做到这一点的查询的?

我有这个代码

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”状态,唯一的问题是我不是这类东西的业余爱好者,所以我很高兴听到你所有的答案。我真的需要你的帮助

4

2 回答 2

3

如果我对您的理解正确,您需要与表进行外部连接(即使没有关联也feeds可以保留所有内容),然后将每个帖子的所有此类提要和所需信息合并在一起。postsfeedsGROUP BY post.pidSELECT

我使用 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
于 2012-05-03T12:13:02.553 回答
2

如果您想为所有用户执行此操作并同时获取提要,则必须加入此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

这个应该可以解决...

于 2012-05-03T12:18:27.510 回答