diff options
Diffstat (limited to 'search.xml')
| -rw-r--r-- | search.xml | 75 |
1 files changed, 57 insertions, 18 deletions
@@ -824,6 +824,45 @@ </tags> </entry> <entry> + <title>N+1 selects problem 与 Prisma ORM</title> + <url>/2025/04/02/N-1-selects-problem-%E4%B8%8E-Prisma-ORM/</url> + <content><![CDATA[<p>N+1 查询问题是指在通过 ORM 查询数据时,执行了<strong>一次</strong>初始查询来获取父对象列表(这 <strong>1</strong> 次查询),然后为列表中的<strong>每一个</strong>父对象都单独执行了一次额外的查询来获取其关联的子对象(这 <strong>N</strong> 次查询)。最终导致总共执行了 <strong>1 + N</strong> 次数据库查询,其中 N 是初始查询返回的父对象的数量。</p> +<p><strong>举个例子:</strong></p> +<p>假设有两个数据库模型:<code>User</code>(用户)和 <code>Post</code>(帖子),一个用户可以有多篇帖子(一对多关系)。</p> +<p>现在,需要获取前 10 个用户以及他们各自的所有帖子。</p> +<p>一种<strong>有问题</strong>的 ORM 实现(或不当的使用方式)可能会这样执行:</p> +<ol> +<li><strong>第一次查询 (The “1”)</strong>: 获取前 10 个用户。<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> <span class="keyword">User</span> LIMIT <span class="number">10</span>;</span><br></pre></td></tr></table></figure></li> +<li><strong>接下来的 N (=10) 次查询 (The “N”)</strong>: 对于上一步获取到的每一个用户,单独执行一次查询来获取该用户的帖子。<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="comment">-- 用户 1</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> Post <span class="keyword">WHERE</span> authorId <span class="operator">=</span> <span class="number">1</span>;</span><br><span class="line"><span class="comment">-- 用户 2</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> Post <span class="keyword">WHERE</span> authorId <span class="operator">=</span> <span class="number">2</span>;</span><br><span class="line"><span class="comment">-- 用户 3</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> Post <span class="keyword">WHERE</span> authorId <span class="operator">=</span> <span class="number">3</span>;</span><br><span class="line"><span class="comment">-- ... 直到 用户 10</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> Post <span class="keyword">WHERE</span> authorId <span class="operator">=</span> <span class="number">10</span>;</span><br></pre></td></tr></table></figure></li> +</ol> +<p>在这个场景下,总共执行了 1 + 10 = <strong>11</strong> 次数据库查询。如果 N 的值很大(比如获取 1000 个用户),就会产生 1001 次查询,这对数据库造成巨大的、不必要的压力,并显著增加应用程序的响应时间。每一次数据库交互都有网络延迟和数据库处理的开销,N+1 次查询会将这些开销放大 N 倍。</p> +<p>N+1 问题通常源于 ORM 处理关联数据的方式,特别是与“懒加载”(Lazy Loading)相关的策略。懒加载是指只有在显式访问关联属性时,ORM 才会去数据库加载这些数据。虽然这在某些情况下可以避免加载不需要的数据,但如果在循环中访问关联属性,就很容易触发 N+1 问题。</p> +<p>然而,问题的根源在于<strong>没有有效地预先加载(或批量加载)所需的关联数据</strong>。即使不使用严格意义上的懒加载,如果 ORM 在处理关联查询时不够智能,采用了逐个获取关联对象的策略,同样会产生 N+1 查询。</p> +<p>在 Prisma 出现之前或在其他 ORM 中,解决 N+1 问题常见的方法包括:</p> +<ol> +<li><strong>预先加载(Eager Loading)</strong>: 在执行初始查询时,就明确指示 ORM 同时将关联数据也查询出来。这通常通过 SQL 的 <code>JOIN</code> 操作实现。例如,一次性查询出用户和他们的帖子。虽然这减少了查询次数,但复杂的 <code>JOIN</code> 可能会导致查询本身变得庞大和低效,并可能返回冗余数据。</li> +<li><strong>批量加载(Batch Loading)</strong>: 先执行初始查询获取父对象列表,然后收集所有父对象的 ID,在第二次查询中使用 <code>WHERE IN (...)</code> 子句一次性加载所有相关的子对象。这种方式通常需要两次查询,但避免了 N 次单独的查询。</li> +</ol> +<p>Prisma ORM 在设计上就考虑了 N+1 问题,并提供了一种既方便开发者又高效的解决方案。当使用 Prisma Client 查询数据并需要包含关联模型时,Prisma 会自动优化查询,<strong>避免产生 N+1 查询</strong>,主要通过<strong>关系查询(Relation Queries)</strong>中的 <code>include</code> 选项或嵌套读取(nested reads)来实现这一点:</p> +<p>假设想获取所有用户及其发布的帖子,使用 Prisma Client,可以这样写:</p> +<figure class="highlight typescript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> { <span class="title class_">PrismaClient</span> } <span class="keyword">from</span> <span class="string">'@prisma/client'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> prisma = <span class="keyword">new</span> <span class="title class_">PrismaClient</span>()</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="keyword">function</span> <span class="title function_">getUsersWithPosts</span>(<span class="params"></span>) {</span><br><span class="line"> <span class="keyword">const</span> usersWithPosts = <span class="keyword">await</span> prisma.<span class="property">user</span>.<span class="title function_">findMany</span>({</span><br><span class="line"> <span class="attr">include</span>: {</span><br><span class="line"> <span class="attr">posts</span>: <span class="literal">true</span>, <span class="comment">// 指示 Prisma 加载关联的 posts</span></span><br><span class="line"> },</span><br><span class="line"> })</span><br><span class="line"> <span class="comment">// usersWithPosts 包含了用户列表,每个用户对象中都有一个 posts 数组</span></span><br><span class="line"> <span class="variable language_">console</span>.<span class="title function_">log</span>(usersWithPosts)</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="title function_">getUsersWithPosts</span>()</span><br><span class="line"> .<span class="title function_">catch</span>(<span class="function">(<span class="params">e</span>) =></span> {</span><br><span class="line"> <span class="keyword">throw</span> e</span><br><span class="line"> })</span><br><span class="line"> .<span class="title function_">finally</span>(<span class="keyword">async</span> () => {</span><br><span class="line"> <span class="keyword">await</span> prisma.$disconnect()</span><br><span class="line"> })</span><br></pre></td></tr></table></figure> + +<p>当执行上述查询时,Prisma <strong>不会</strong> 生成 N+1 个 SQL 查询。而是首先会分析请求,并将其转化为数量非常有限的高效 SQL 查询。对于上面这个一对多关系的 <code>include</code> 查询,Prisma 通常会执行以下<strong>两步</strong>(类似于批量加载策略):</p> +<ol> +<li><strong>查询父模型</strong>: 获取所有 <code>User</code> 记录。<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> "public"."User"."id", "public"."User"."name", <span class="comment">/* ... other user fields */</span> <span class="keyword">FROM</span> "public"."User" <span class="keyword">WHERE</span> <span class="number">1</span><span class="operator">=</span><span class="number">1</span></span><br></pre></td></tr></table></figure></li> +<li><strong>查询关联的子模型</strong>: 使用上一步获取到的所有用户 <code>id</code>,通过 <code>WHERE IN (...)</code> 子句一次性查询所有相关的 <code>Post</code> 记录。<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> "public"."Post"."id", "public"."Post"."title", "public"."Post"."authorId", <span class="comment">/* ... other post fields */</span> <span class="keyword">FROM</span> "public"."Post" <span class="keyword">WHERE</span> "public"."Post"."authorId" <span class="keyword">IN</span> ($<span class="number">1</span>, $<span class="number">2</span>, $<span class="number">3</span>, ...) <span class="comment">/* 这里的 $1, $2, ... 是第一步查到的用户 ID 列表 */</span></span><br></pre></td></tr></table></figure></li> +</ol> +<p>Prisma Client 在内存中将这两次查询的结果高效地组合起来,最终返回嵌套的、符合 TypeScript 类型的数据。</p> +<h2 id="Refs"><a href="#Refs" class="headerlink" title="Refs."></a>Refs.</h2><ul> +<li><a href="https://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem-in-orm-object-relational-mapping">Stack Overflow: What is the N+1 selects problem in ORM?</a></li> +<li><a href="https://www.prisma.io/docs/orm/prisma-client/queries/query-optimization-performance#solving-the-n1-problem">Prisma Docs: Solving the N+1 problem</a></li> +</ul> +]]></content> + <tags> + <tag>Technique</tag> + </tags> + </entry> + <entry> <title>.NET AOT 下的 F# 命令行参数解析库选择</title> <url>/2024/06/06/NET-AOT-%E4%B8%8B%E7%9A%84-F-%E5%91%BD%E4%BB%A4%E8%A1%8C%E5%8F%82%E6%95%B0%E8%A7%A3%E6%9E%90%E5%BA%93%E9%80%89%E6%8B%A9/</url> <content><![CDATA[<p>Argu 不支持 AOT,不过用 F# 的话可以看整个 .NET 的生态,我看了一下 C# 的 CommandLineParser:<br><a href="https://github.com/commandlineparser">https://github.com/commandlineparser</a></p> @@ -3086,6 +3125,24 @@ </categories> </entry> <entry> + <title>二零二零年十二月九日</title> + <url>/2020/12/09/%E4%BA%8C%E9%9B%B6%E4%BA%8C%E9%9B%B6%E5%B9%B4%E5%8D%81%E4%BA%8C%E6%9C%88%E4%B9%9D%E6%97%A5/</url> + <content><![CDATA[<p>我们走在朝阳的洪流上, 一步一个脚印, 踏散阳光, 向南是北。</p> +]]></content> + <categories> + <category>gallery</category> + </categories> + </entry> + <entry> + <title>二零二零年十二月二十六日</title> + <url>/2020/12/26/%E4%BA%8C%E9%9B%B6%E4%BA%8C%E9%9B%B6%E5%B9%B4%E5%8D%81%E4%BA%8C%E6%9C%88%E4%BA%8C%E5%8D%81%E5%85%AD%E6%97%A5/</url> + <content><![CDATA[<p>我被包裹在吊床中,两颗香樟树支撑着它,仲夏的热浪砸在粗壮的香樟树上,叶子一屈,抱住了热浪,可随即而来的是不知从哪浇来的阳光,叶子承受不住这样的力量,被砸的孔洞百出,砸的香气落满树下的人间。</p> +]]></content> + <categories> + <category>gallery</category> + </categories> + </entry> + <entry> <title>二零二零年十二月八日</title> <url>/2020/12/08/%E4%BA%8C%E9%9B%B6%E4%BA%8C%E9%9B%B6%E5%B9%B4%E5%8D%81%E4%BA%8C%E6%9C%88%E5%85%AB%E6%97%A5/</url> <content><![CDATA[<p>它们勇敢的站在烈日下, 像人类一样无所畏惧, 却又恐惧的躲在黑暗中, 像当初的它们一样无处可逃。</p> @@ -5896,24 +5953,6 @@ </tags> </entry> <entry> - <title>二零二零年十二月九日</title> - <url>/2020/12/09/%E4%BA%8C%E9%9B%B6%E4%BA%8C%E9%9B%B6%E5%B9%B4%E5%8D%81%E4%BA%8C%E6%9C%88%E4%B9%9D%E6%97%A5/</url> - <content><![CDATA[<p>我们走在朝阳的洪流上, 一步一个脚印, 踏散阳光, 向南是北。</p> -]]></content> - <categories> - <category>gallery</category> - </categories> - </entry> - <entry> - <title>二零二零年十二月二十六日</title> - <url>/2020/12/26/%E4%BA%8C%E9%9B%B6%E4%BA%8C%E9%9B%B6%E5%B9%B4%E5%8D%81%E4%BA%8C%E6%9C%88%E4%BA%8C%E5%8D%81%E5%85%AD%E6%97%A5/</url> - <content><![CDATA[<p>我被包裹在吊床中,两颗香樟树支撑着它,仲夏的热浪砸在粗壮的香樟树上,叶子一屈,抱住了热浪,可随即而来的是不知从哪浇来的阳光,叶子承受不住这样的力量,被砸的孔洞百出,砸的香气落满树下的人间。</p> -]]></content> - <categories> - <category>gallery</category> - </categories> - </entry> - <entry> <title>关于</title> <url>/about.html</url> <content><