简体   繁体   English

PHP查询以联接多个表行

[英]PHP query to Join multiple Table rows

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. 我也想获取每个帖子的UserInfo以及帖子的其他字段。

Currently in JSON i am getting above fields, but If i want to add an extra field "user" and pass user to it eg 当前在JSON中,我正在上面的字段,但是如果我想添加一个额外的字段“用户”并将用户传递给它,例如

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? 我可以设法做得更有效吗?还是只用一个查询?

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. 这样做的基本前提是您提取所有相关的用户ID,执行一次查询以找到相关的用户,然后将这些用户重新分配回原始数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM