所以我现在正在编写一个类似于新闻提要的推文,但问题是我自己的帖子在帖子之前显示了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次。我该如何解决这个问题?
答案 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