[英]3 tables in one mysql query?
我的mysql查询代码需要帮助! 我有三个数据库,我试图找到一种方法来发布这三个数据库中的数据。
users ---------------------------------- user_id username email..etc ----------------------------------- 1 username ----------------------------------- friends_db ------------------------------------- user_id friend_id friend_active -------------------------------------- 1 2 1 -------------------------------------- posts ------------------------------------- post_id user_id post_content ------------------------------------- 1 1 this is a post --------------------------------------
我想做的是创建一个朋友帖子列表,您可以在其中看到您的朋友(在friend_active中为1的朋友)所做的所有帖子。
我的功能:
function getFriendsPosts()
{
require "config.php";
$friends = $c->query ( "SELECT * FROM friends_db WHERE user_id=" . $_SESSION["user_id"] ." AND friend_active = 1" ) ;
if ( $friends->num_rows > 0 )
{
while( $row = $friends->fetch_assoc() )
{
$postData[] = array( "user_id" => $row[ "user_id" ], "friend_active" => $row[ "friend_active" ], "friend_id" => $row[ "friend_id" ] );
}
} else {
echo "No Data To Show";
}
return $postData;
}
我有:
$friends = $c->query ( "SELECT * FROM friends_db WHERE user_id=" . $_SESSION["user_id"] ." AND friend_active = 1" ) ;
这给了我具有friend_active = 1的任何人的user_id
但是我不知道如何通过将friend_id与他们自己的user_id相关联来扩展此名称,以获取他们的用户名,然后在其中也将显示其帖子。
我可能不太复杂,或者可能不是,我不知道。 有谁知道我可以用已经做过的相同格式来做到这一点(我还有其他事情要处理这种格式,我也需要这样做)? 还是有一些建议?
编辑:
$friends = getFriendsPosts();
foreach ($friends as $friend) {
?>
<div class="ui-corner-all custom-corners">
<div id="searchpost">
<?php
echo $friend['user_id'];
echo $friend['friend_id'];
echo $friend['friend_active'];
?>
</div>
</div>
<?php
}
?>
我想:
echo用户名(与friend_id /自己的用户ID有关)echo post数据(与user_id有关)
我假设查询中的friends_db
部分实际上是friends
表?我还假设这些表之间存在关系:
如果是这样,您可以使用联接:
select * from friends as f
join users as u on u.user_id = f.user_id
join posts as p on p.user_id = f.user_id
where f.user_id = ...
或者,获取您的朋友的帖子:
select * from posts as p
join users as u on u.user_id = p.user_id //gets users table where related to posts
join friends as f on f.user_id = p.user_id //gets friends where related
join users as fu on fu.user_id = f.friend_id //gets users table where related to friend user_id
where u.user_id = ....//the sources user_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.