MYSQL查询 - 获取当前用户的帖子以及用户关注的帖子

时间:2016-10-27 13:36:18

标签: php mysql

我正在尝试查询以获取当前用户的帖子以及他关注的人的帖子。像大多数社交网络一样在他们的主页上。

我知道如何查询所有当前用户的帖子,但我很难让用户关注帖子。

我看到了另一个问题Mysql select query for getting current user post and followed friend post

但那里的答案并没有真正帮助我......

到目前为止,这是我的查询:

SELECT P.id, 
P.caption,
P.date,
U.id,
U.fullname,
U.username,
F.IdOtherUser
FROM USERS AS U
INNER JOIN Activity AS F
ON U.id = F.id
INNER JOIN Posts AS P 
ON P.id = U.id OR P.id = F.IdOtherUser
WHERE P.id = 145
ORDER BY P.id DESC

145 =当前用户。

Activity.IdOtherUser =用户' 145'正在关注

Activity.id =将是' 145'当前用户

如果有人可以帮助我解决这个问题,我会很感激!

似乎无法完全理解它,因为我对MYSQL很新......

修正

(SELECT P.id as postid, 
        P.caption,
        P.date,
        U.id as userid,
        U.fullname,
        U.username,
        coalesce(Activity.LikeCNT,0),
        Activity.CurrentUserLiked
        FROM USERS AS U
        INNER JOIN Posts AS P 
        ON P.id = U.id
        LEFT JOIN (SELECT COUNT(DISTINCT Activity.uuidPost) LikeCNT, Activity.uuidPost, Activity.id, sum(CASE WHEN Activity.id = 145 then 1 else 0 end) as CurrentUserLiked
        FROM Activity Activity
        WHERE type = 'like' 
        GROUP BY Activity.uuidPost) Activity
        ON Activity.uuidPost = P.uuid
        AND Activity.id = U.id
        WHERE U.id = 145)
UNION
(SELECT P.id, 
        P.caption,
        P.date,
        U.id,
        U.fullname,
        U.username,
        coalesce(Activity.LikeCNT,0),
        Activity.CurrentUserLiked
        FROM Activity AS A
        INNER JOIN USERS AS U 
        ON A.IdOtherUser=U.id
        INNER JOIN Posts AS P 
        ON P.id = U.id
        LEFT JOIN (SELECT COUNT(DISTINCT Activity.uuidPost) LikeCNT, Activity.uuidPost, Activity.id, sum(CASE WHEN Activity.id = 145 then 1 else 0 end) as CurrentUserLiked
    FROM Activity Activity
    WHERE type = 'like' 
    GROUP BY Activity.uuidPost) Activity
    ON Activity.uuidPost = P.uuid
    AND Activity.id = U.id
    WHERE A.id = 145)

1 个答案:

答案 0 :(得分:0)

要获取给定用户的所有帖子(id = 145)及其跟随的所有用户的帖子,以及每篇帖子的用户详细信息,我会重写查询以使用union代替或从而简化了逻辑。第一个选择获取给定用户的帖子,第二个获取它所关注的用户的帖子:

(SELECT P.id as postid, 
       P.caption,
       P.date,
       U.id as userid,
       U.fullname,
       U.username,
FROM USERS AS U
INNER JOIN Posts AS P ON P.userid = U.id
WHERE U.id = 145)
UNION
(SELECT P.id, 
       P.caption,
       P.date,
       U.id,
       U.fullname,
       U.username,
FROM Activity AS A
INNER JOIN USERS AS U ON A.IdOtherUser=U.id
INNER JOIN Posts AS P ON P.userid = U.id
WHERE A.id = 145)
ORDER BY postid DESC

假设:

  1. Activity.id字段表示跟随其他用户的用户。如果没有,您需要将字段名称更改为适当的名称。

  2. 发明了Posts表的userid字段,表示发布帖子的用户。请使用正确的字段名称。