欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

今天,注意到mysql N+1优化

程序员文章站 2024-03-15 16:02:48
...

进行优化时,注意到mysql N+1优化流程:先查询1次用户列表、取出列表中的课程ID组成数组、查询课程、合并数据

$users = “select * from user”;

$course_ids = [];

foreach($users as $user) {

if(!in_array($user[‘course_id’], $course_ids)){

   $course_ids[] = $user['course_id'];

}

}

$courses = “select * from course where id in (’.join(’,’, $course_id).’)”;

$map = [];

foreach($courses as $course) {

$map[$course['course_id']] = $course;

}

foreach($users as $user) {

$map['course'] = $map[$user['course_id']] ?? null;

}

相关标签: N+1优化