今天,注意到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;
}
上一篇: 求100以内的全部素数
下一篇: 求n 的阶乘