在MySQL代码中遇到一些问题,试图从我自己跟随的人那里获取数据

时间:2013-07-13 16:12:06

标签: mysql sql

所以我现在正在编写一个类似于新闻提要的推文,但问题是我自己的帖子在帖子之前显示了4次(以下有4个条目我认为这就是为什么它显示我的帖子4次)

SELECT * 
FROM following AS f, posts AS p 
WHERE p.post_user_id = 1 OR 
      (f.follower_id = p.post_user_id AND f.user_id = 1) 
ORDER BY  `p`.`post_time` DESC 

所以这是我目前的代码。虽然我认为它错了,因为它会显示我的帖子4次。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

由于您在OR条件中使用JOIN,我相信您在Cartesian Product时收到post_user_id = 1。尝试这样的事情:

SELECT * 
FROM following AS f
    JOIN posts AS p ON f.follower_id = p.post_user_id
WHERE p.post_user_id = 1 OR f.user_id = 1 
ORDER BY  p.post_time DESC 

答案 1 :(得分:1)

因为看起来您真的不关心following中的字段而只想要帖子,所以如何使用LEFT JOIN

SELECT p.* 
FROM posts p
LEFT JOIN following f ON f.follower_id=1 AND p.post_user_id = f.user_id
WHERE post_user_id=1 OR f.user_id IS NOT NULL
ORDER BY  `p`.`post_time` DESC 

An SQLfiddle to test with