小淦妈妈 發表於 2025-7-8 21:59:00

INNER JOIN, LEFT JOIN, RIGHT JOIN 的区别

<p><span id="cke_bm_543S"></span>今天我们来一起探索下<strong> JOIN,JOIN&nbsp;</strong>作为数据库操作的核心概念,用于合并两个或多个表中的数据。</p>
<p>一、<strong>JOIN (INNER JOIN)</strong></p>
<p>1、<strong>基本功能:</strong>返回两个表中<strong>匹配</strong>成功的行。</p>
<p>2、<strong>特点:</strong></p>
<ul>
<li>只保留两表中<strong>都满足</strong>连接条件的记录;</li>
<li>如果某行在一个表中存在但在另一个表中没有匹配项,则该行不会出现在结果中;</li>
<li>结果集的行数<strong> ≤ </strong>两个原表的行数。</li>
</ul>
<p>3、<strong>语法</strong>:</p>
<pre class="language-sql highlighter-hljs"><code>SELECT columns
FROM table1
JOIN table2 ON table1.column = table2.column;</code></pre>
<p>4、<strong>示例</strong>:</p>
<pre class="language-sql highlighter-hljs"><code>SELECT orders.order_id, customers.customer_name
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id;</code></pre>
<p><strong>二、LEFT JOIN (LEFT OUTER JOIN)</strong></p>
<p><strong>1、基本功能</strong>:返回左表的所有行,即使右表中没有匹配。</p>
<p><strong>2、特点</strong>:</p>
<ul>
<li>保留左表的全部记录;</li>
<li>当右表无匹配时,右表字段显示为 <strong>NULL</strong>;</li>
<li>结果集的行数<strong> = </strong>左表的行数。</li>
</ul>
<p><strong>3、语法</strong>:</p>
<pre class="language-sql highlighter-hljs"><code>SELECT columns
FROM table1
LEFT JOIN table2 ON table1.column = table2.column;</code></pre>
<p><strong>4、示例</strong>:</p>
<pre class="language-sql highlighter-hljs"><code>SELECT employees.name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.dept_id = departments.dept_id;</code></pre>
<p>三、<strong>RIGHT JOIN (RIGHT OUTER JOIN)</strong></p>
<p><strong>1、基本功能</strong>:返回右表的所有行,即使左表中没有匹配。</p>
<p><strong>2、特点</strong>:</p>
<ul>
<li>保留右表的全部记录;</li>
<li>当左表无匹配时,左表字段显示为 <strong>NULL</strong>;</li>
<li>结果集的行数<strong> = </strong>右表的行数;</li>
<li>实际使用较少,通常可以用 LEFT JOIN 替代。</li>
</ul>
<p><strong>3、语法</strong>:</p>
<pre class="language-sql highlighter-hljs"><code>SELECT columns
FROM table1
RIGHT JOIN table2 ON table1.column = table2.column;</code></pre>
<p><strong>4、示例</strong>:</p>
<pre class="language-sql highlighter-hljs"><code>SELECT employees.name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.dept_id = departments.dept_id;</code></pre>
<p><strong>实际使用建议</strong></p>
<ul>
<li><strong>INNER JOIN </strong>是最常用的,适用于需要两个表都有数据的场景;</li>
<li><strong>LEFT JOIN</strong> 常用于需要主表完整数据,关联表可有可无的情况;</li>
<li><strong>RIGHT JOIN</strong> 使用较少,通常可以通过调换表顺序用 LEFT JOIN 实现;</li>
<li>注意 <strong>NULL </strong>值的处理,特别是在 WHERE 条件中。</li>
</ul>
<p style="text-align: right"><span style="color: rgba(53, 152, 219, 1)">在强者的世界中,即便是戴着镣铐跳舞,舞也会跳得铿锵有力。-- 烟沙九洲</span></p><br><br>
来源:https://www.cnblogs.com/yanshajiuzhou/p/18973937
頁: [1]
查看完整版本: INNER JOIN, LEFT JOIN, RIGHT JOIN 的区别