我有3张桌子:
users
user_id
first_name
forum_post
post_id
post_title
user_post_join
id
user_id
post_id
连接表从用户获取user_id,从forum_posts获取post_id。
我想要显示的是forum_post表和发布它的用户的帖子列表。我很难知道加入应该在哪里,这是我到目前为止的尝试......
function build_forum_posts(){
global $dbc;
$q = "SELECT users.user_id, forum_post.post_id, user_post_join.id
FROM users
INNER JOIN user_post_join ON users.user_id = forum_posts.post_id
";
$r = mysqli_query ($dbc, $q); // Run the query.
// FETCH AND PRINT ALL THE RECORDS
while ($row = mysqli_fetch_array($r)) {
echo '
<div class="post">
<div class="col-group-2">
<h3>'.$row["post_id"]. '</h3>
<p>By: '.$row["user_id"]. '</p>
</div>
<div class="col-group-2">
<div class="post_count">
<h3 class="answer">0</h3>
<p class="answer">Answers</p>
</div>
</div>
</div>
';
}
答案 0 :(得分:2)
您没有加入所有三张桌子。尝试这样的事情:
SELECT u.user_id, u.first_name, f.post_id, f.post_title, j.id
FROM users AS u
INNER JOIN user_post_join AS j ON u.user_id = j.user_id
INNER JOIN forum_posts AS f ON f.post_id = j.post_id