duannei1477 2013-12-11 05:51
浏览 15
已采纳

PHP查询加入多个表行

I am using following code to query

 $statement = $conn->prepare('SELECT * FROM userFeeds WHERE userId = :userId ORDER BY creationDate ASC LIMIT 100');
                $statement->bindParam(':userId'    , $userId, PDO::PARAM_STR);
                $statement->execute();
                $posts = $statement->fetchAll(PDO::FETCH_ASSOC);

                return array('Success'=>$row, 'Posts'=>$posts);

Each post has following feilds,

id   userId   comment  type  date

I also want to get the UserInfo of each post along with the other fields of posts.

Currently in JSON i am getting above fields, but If i want to add an extra field "user" and pass user to it e.g

foreach ($post in $posts)
{
   // PERFORM A QUERY TO GET USER FROM post=>userId
    $post['user'] = $user;
}

This loop could be a long thing. Can I manage to do something more efficiently or in one query only?

  • 写回答

1条回答 默认 最新

  • duanpin2034 2013-12-11 08:14
    关注

    Whenever I've been faced with something similar to this, the code snippet below is an example of how I solve it, and reduce the number of queries:

    # build an array of user ids
    $userIds = array();
    foreach ($posts as $post) {
        if (!in_array($post['userId'], $userIds)) {
            $userIds[] = (int)$post['userId'];
        }
    }
    
    # fetch these users.
    $st = $conn->query('SELECT * FROM `users` WHERE `id` IN (' . implode(',', $userIds) . ')';
    while ($row = $st->fetch(PDO::FETCH_ASSOC)) {
        $users[] = $row;
    }
    
    # assign users to posts.
    foreach ($posts as $index => $post) {
        $posts[$index]['user'] = null;
        foreach ($users as $user) {
            if ($user['id'] == $post['userId']) {
                $posts[$index]['user'] = $user;
                break;
            }
        }
    }
    

    The basic premise of this is that you extract all the relevant user ids, perform a single query to find the relevant users, and then re-assign those users back into the original array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序