【问题标题】:Return all the posts of people followed by user MySQL返回用户 MySQL 关注的所有人员的帖子
【发布时间】:2016-10-19 02:23:07
【问题描述】:

我有三张桌子

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 查询并避免使用数组的建议。

【问题讨论】:

    标签: php mysql join


    【解决方案1】:

    选择您需要的字段

    SELECT f.*, p.*
    FROM table_follows f
    JOIN table_posts p
      ON f.id_followed = p.id_user 
    WHERE f.id_follower = '3'
    

    【讨论】:

    • ON f.id_follow(er) = p.id_user ?
    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 2017-04-03
    • 1970-01-01
    相关资源
    最近更新 更多