我有三个表
table_users: id_user | name
table_posts: id_post | id_user | post
table_follows: id_follow | id_follower | id_followed
第一个表显示用户,第二个表显示他们发布的帖子,第三个表映射用户之间的关系(关注者/被关注者)。
例如,如果我有用户 Mattew id=3
,我想检索他关注的所有人“发布”的帖子。在这种情况下,Adam id=1
、Tom id=7
和 Zoe id=9
后面是 Mattew。
我已经开发了一个有效的 php/mysql
代码,但我想只使用一个 SQL 语句来改进它。
//retrieve all the people followed by Mattew
$followeds=mysql_query("SELECT * FROM table_follows WHERE id_follower='3' /*Mattew*/");
//create an array with the ids
$array_followeds=array();
while($fwd=mysql_fetch_array($followeds)){
$id_followed=$fwd['id_followed'];
$array_followeds[]="id_user='".$id_followed."'";
}
//if exists people followed by Mattew
if(count($array_followeds)>0){
$array_followeds=implode(' OR ', $array_followeds);
}else{/*$array_followeds="id_user=0";*/}
//main query: shows all the posts of the people Mattew follows
$main_query=mysql_query("SELECT * FROM $table_posts WHERE ($array_followeds) AND id_user!='3'/*Mattew*/");
while($posts=mysql_fetch_array($main_query)){
/*results */
}
我想要有关如何使用单个语句改进 SQL 查询并避免使用数组的建议。
最佳答案
选择你需要的字段
SELECT f.*, p.*
FROM table_follows f
JOIN table_posts p
ON f.id_followed = p.id_user
WHERE f.id_follower = '3'
关于php - 返回用户 MySQL 关注的人的所有帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40121038/