我正在尝试按照userID(查询中的?
)后面的用户获取帖子,并由?
用户自己获取帖子。
SELECT
posts.id AS postid, posts.user AS user, posts.images AS images, posts.post_created, posts.textvalue, posts.textpost,
users.username AS authorname
FROM posts
INNER JOIN follows ON (posts.user = follows.follows AND follows.user = ?) OR posts.user = ?
INNER JOIN users ON users.id = posts.user
ORDER BY posts.post_created DESC LIMIT 20
此查询有效,但是对于?
的每个帖子,它都会返回该行两次,当我删除OR posts.user = ?
时,它可以正常工作,但不会显示?
的帖子用户身份。
答案 0 :(得分:0)
我相信你想要
SELECT p.*, u.username AS authorname
FROM posts p INNER JOIN
users u
ON u.id = p.user LEFT JOIN
follows f
ON p.user = f.follows AND f.user = ?
WHERE f.user IS NOT NULL OR -- a match on the "follows" condition
p.user = ? -- a match on the post condition
ORDER BY p.post_created DESC
LIMIT 20;
您的查询是一个令人困惑的问题。但基本上,您对于来自用户的帖子具有以下条件:
FROM posts p INNER JOIN
follows f
ON p.user = ?
(忘记OR
部分-只会进一步增加行数。)
两个表之间没有JOIN
条件,因此在该帖子后面的每个用户都会得到一行。