我正在尝试从当前用户关注的人员及其详细信息中检索帖子。我一直在研究,似乎加入是正确的方法,但我不确定它有什么问题。
这是我的代码
$queryfeed = "SELECT posts.user_id, posts.body, posts.image, posts.has_image
FROM posts, follows WHERE posts.user_id = follows.leader_id
AND follows.follower_id =$user_id INNER JOIN users ON users.user_id
= follows.leader_id";
$resultfeed = $db->query($queryfeed);
if($resultfeed->num_rows > 0) {
while( $rowfeed = $resultfeed->fetch_assoc() ) {
if($rowfeed['posts.has_image'] == 1) {
?>
<article class="post">
<div class="post-head cf">
<a class="userpic" href=""><img src="<?php echo $userpic ?>" alt="<?php echo $rowfeed['users.username'] ?>"></a>
<a href="" class="username">
<?php echo $rowfeed[users.'username']; ?>
</a>
</div>
<img src="users/user_<?php echo $rowfeed['posts.user_id'] ?>/posts/<?php echo $rowfeed['posts.image']; ?>" alt="">
<div class="post-body">
<div class="post-options">
<a class="likes" href="">2 likes</a>
</div>
<p>
<a class="username" href="">
<?php echo $rowfeed['users.username'] ?>
</a>
<?php echo $rowfeed['posts.body'] ?>
</p>
<hr />
<div class="cf">
<a class="like hide-text" href="javascript:;">Like This Post</a>
<form action="" class="comment">
<input type="text" placeholder="Add a comment">
</form>
</div>
</div>
</article>
<?php } else { ?>
我的表格看起来像这样
users
user_id | username | avatar
posts
post_id | user_id | body | image | has_image
follows
leader_id | follower_id
答案 0 :(得分:1)
从您的原始查询中,我发现您只对帖子的数据感兴趣(而不是发布帖子的用户的数据)。我假设$ user_id保存当前用户的id,即也用作follower_id的值。如果是这种情况,查询会变得更容易:
SELECT p.user_id, p.body, p.image, p.has_image
FROM followers f INNER JOIN posts p ON f.leader_id = p.user_id and f.follower_id = $user_id
如果您对海报的用户数据感兴趣,请按以下步骤更改查询:
SELECT p.user_id, p.body, p.image, p.has_image, u.username, u.avatar
FROM follows f
INNER JOIN posts p ON f.leader_id = p.user_id and f.follower_id = $user_id
INNER JOIN users u ON p.user_id = u.user_id
答案 1 :(得分:0)
我现在无法访问计算机,但似乎您的SQL-Query有一些错误。看看我的更正版本:
SELECT posts.user_id, posts.body, posts.image, posts.has_image FROM posts
INNER JOIN follows ON posts.user_id = follows.follower_id
WHERE follows.leader_id=$user_id;
答案 2 :(得分:0)
尝试此查询:
SELECT
posts.user_id, posts.body, posts.image, posts.has_image
authors.avatar, authors.username
FROM
posts
LEFT JOIN
users as authors
ON
authors.user_id=posts.user_id
LEFT JOIN
follows
ON
follows.leader_id=authors.user_id
WHERE
follows.follower_id={$user_id}
仅使用LEFT JOIN ....
答案 3 :(得分:0)
让我们假设当前的user.user_id为1,关注者为user.user_id 2,3和4
我认为我们需要符合以下标准吗?
posts.user_id = follows.follower_id
follows.leader_id = $user_id
所以查询需要这样吗?
SELECT *
FROM posts
INNER JOIN follows
ON posts.user_id = follows.follower_id
INNER JOIN users
ON follows.leader_id = $user_id
以下是表格的模拟示例
=== users ===
user_id | username | avatar
1 current
2 fake1
3 fake2
4 fake3
=== posts ===
post_id | user_id | body | image | has_image
1 2
2 2
3 3
4 3
5 4
6 4
=== follows ===
leader_id | follower_id
1 2
1 3
1 4
那有意义吗?由于当前用户($ user_id)是关注者的领导者,因此如果您希望关注者的帖子而不是帖子,则follower_id将需要成为帖子的用户领导者......