Rails에서 N+1 문제를 해결하는 방법
13611 단어 railsrubysqlperformance
🤨 N+1 문제란?
Kaziu ・ 4월 1일 ・ 1분 읽기
#sql
#beginners
#database
#mysql
🔑 4가지 주요 방법
💎 조인
INNER JOIN으로 통합
Skill.joins(:skill_category).limit(5)
↓
SELECT "skills".*
FROM "skills"
INNER JOIN "skill_categories"
ON "skill_categories"."id" = "skills"."skill_category_id"
LIMIT ? [["LIMIT", 5]]
💎 열망하는_부하
캐시와 LEFT OUTER JOIN으로 통합
Skill.eager_load(:skill_category).limit(5)
↓
SELECT "skills"."id" AS t0_r0, "skills"."name" AS t0_r1, "skills"."user_id" AS t0_r2, "skills"."skill_category_id" AS t0_r3, "skills"."created_at" AS t0_r4, "skills"."updated_at" AS t0_r5, "skill_categories"."id" AS t1_r0, "skill_categories"."name" AS t1_r1, "skill_categories"."reccomend" AS t1_r2, "skill_categories"."created_at" AS t1_r3, "skill_categories"."updated_at" AS t1_r4
FROM "skills"
LEFT OUTER JOIN "skill_categories"
ON "skill_categories"."id" = "skills"."skill_category_id"
LIMIT ? [["LIMIT", 5]]
💎 프리로드
캐시와 함께 여러 SQL 사용
Skill.preload(:skill_category).limit(5)
↓
# this one
SELECT "skills".* FROM "skills" LIMIT ? [["LIMIT", 5]]
# and this one
SELECT "skill_categories".*
FROM "skill_categories"
WHERE "skill_categories"."id"
IN (?, ?, ?, ?, ?) [[nil, 483], [nil, 583], [nil, 901], [nil, 181], [nil, 147]]
💎 포함
where, join, 적어도 하나의 방법을 사용하면 eager_load로 실행되고, 그렇지 않으면 미리 로드됩니다.
# just includes
Skill.includes(:skill_category).limit(5)
↓
# this one
SELECT "skills".* FROM "skills" LIMIT ? [["LIMIT", 5]]
# and this one
SELECT "skill_categories".*
FROM "skill_categories"
WHERE "skill_categories"."id"
IN (?, ?, ?, ?, ?) [[nil, 483], [nil, 583], [nil, 901], [nil, 181], [nil, 147]]
# using where()
Skill.includes(:skill_category).where(skill_categories: { name: 'baseball' })
↓
# just one SQL like eager_load 👍
SELECT "skills"."id" AS t0_r0, "skills"."name" AS t0_r1, "skills"."user_id" AS t0_r2, "skills"."skill_category_id" AS t0_r3, "skills"."created_at" AS t0_r4, "skills"."updated_at" AS t0_r5, "skill_categories"."id" AS t1_r0, "skill_categories"."name" AS t1_r1, "skill_categories"."reccomend" AS t1_r2, "skill_categories"."created_at" AS t1_r3, "skill_categories"."updated_at" AS t1_r4
FROM "skills"
LEFT OUTER JOIN "skill_categories"
ON "skill_categories"."id" = "skills"."skill_category_id"
WHERE "skill_categories"."name" = ? [["name", "baseball"]]
includes 방식은 보시다시피 편리하지만 다른 개발자가 include 방식을 볼 때 "preload"또는 "eager_load"를 의미한다고 생각해야 합니다.
Reference
이 문제에 관하여(Rails에서 N+1 문제를 해결하는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/kaziusan/how-to-resolve-n1-problem-on-rails-fl2텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)