dongluedeng1524 2018-09-05 12:09
浏览 46
已采纳

显示关注者和登录用户的帖子

I want to display posts from the users being followed and the logged in user using a single PHP mysql query.

I have three tables:
- Users (id, name, password)
- Posts (id, body, date, user_id)
- Followers (id, user_id, follower_id)

followers.follower_id = person who does the following
followers.user_id = person who is being followed
$_SESSION['id'] = id of the logged in user

DB::query('
SELECT users.name, posts.body 
FROM users, posts, followers 
WHERE posts.user_id = followers.user_id 
AND users.id = posts.user_id 
AND followers.follower_id = :userid', 
array(':userid'=>$_SESSION['id'])
);

But the query only shows posts from the users being followed, not from the logged in user. How do I fix this?

I have already created a relation between the posts table and the users table.

CREATE TABLE `posts` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `body` varchar(160) NOT NULL DEFAULT '',
  `user_id` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
  • 写回答

1条回答 默认 最新

  • dsilhx5830 2018-09-05 13:21
    关注

    You need to include 2 criteria in your WHERE clause: Either the creator of the post matches your :userid variable, or the follower matches your :userid.

    Please use current join syntax: This makes your query a lot easier to read.

    Your final query should be something like this (I'm excluding the PHP part):

    SELECT users.name, posts.body
    FROM posts
        INNER JOIN users ON
            users.id = Posts.user_id
        -- use left join to handle when a 
        -- user has no followers
        LEFT JOIN Followers ON
            Followers.user_id = users.user_id
    WHERE
        users.id = :userid
        OR followers.follower_id = :userid
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器