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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行