Solve database N+1 query problem

步履不停
Release: 2019-06-19 09:41:50
Original
9789 people have browsed it

Solve database N+1 query problem

Requirements

The data table is as follows:

department table

|id|name|

user table

|id|name|department_id|

The requirement is to obtain data with the following structure:

[
    {        "id":1,        "name":"test",        "department_id":1,        "department":{            "id":1,            "name":"测试部门"
        }
    }
]
Copy after login

Method 1: Loop query

  1. Query user list

  2. Loop user list to query corresponding department information

$users = $db->query('SELECT * FROM `user`');foreach($users as &$user) {
    $users['department'] = $db->query('SELECT * FROM `department` WHERE `id` = '.$user['department_id']);
}
Copy after login

The number of queries for this method is: 1 N (1 query list , N query departments), the performance is the lowest and not advisable.

方法二:连表

  1. 通过连表查询用户和部门数据

  2. 处理返回数据

$users = $db->query('SELECT * FROM `user` INNER JOIN `department` ON `department`.`id` = `user`.`department_id`');// 手动处理返回结果为需求结构
Copy after login

该方法其实也有局限性,如果 userdepartment 不在同一个服务器是不可以连表的。

方法三:1+1查询

  1. 该方法先查询1次用户列表

  2. 取出列表中的部门ID组成数组

  3. 查询步骤2中的部门

  4. 合并最终数据

代码大致如下:

$users = $db->query('SELECT * FROM `user`');
$departmentIds =[ ];foreach($users as $user) {    if(!in_array($user['department_id'], $departmentIds)) {
        $departmentIds[] = $user['department_id'];
    }
}
$departments = $db->query('SELECT * FROM `department` WHERE id in ('.join(',',$department_id).')');
$map = []; // [部门ID => 部门item]foreach($departments as $department) {
    $map[$department['id']] = $department;
}foreach($users as $user) {
    $user['department'] = $map[$user['department_id']] ?? null;
 }
Copy after login

该方法对两个表没有限制,在目前微服务盛行的情况下是比较好的一种做法。

更多MySQL相关技术文章,请访问MySQL教程栏目进行学习!

The above is the detailed content of Solve database N+1 query problem. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!