SQL 连接和窗口函数

发布: (2026年3月3日 GMT+8 00:19)
4 分钟阅读
原文: Dev.to

I’m happy to help translate the article, but I need the full text you’d like translated. Could you please paste the content (excluding the source line you’ve already provided) here? Once I have the article text, I’ll translate it into Simplified Chinese while preserving the formatting, markdown, and any code blocks.

介绍

SQL joins 用于基于相关列合并多个表的数据。

Window functions 在与当前行相关的一组表行上执行计算,实现逐行聚合而不压缩数据。

在本文中,您将深入了解 SQL joins 和 window functions 的工作原理、何时使用它们以及它们如何解决实际业务问题。让我们开始吧。

SQL 连接类型

有四种主要的 SQL 连接方式。

内连接

仅返回两个表中具有匹配值的记录。

内连接示例

业务问题

哪些客户已经下过订单?

假设我们有两个表:

  • Customers(客户)
  • Orders(订单)

客户与订单表

示例数据

查询

SELECT c.customer_id,
       c.customer_name,
       o.order_id
FROM   customers c
INNER JOIN orders o
       ON c.customer_id = o.customer_id;

结果

内连接结果

Tim Adagala 未出现在结果中,因为他没有订单。

左连接

返回左表的所有记录以及右表中匹配的行。

左连接示意图

业务问题

显示所有客户,即使他们尚未下单。

查询

SELECT c.customer_id,
       c.customer_name,
       o.order_id
FROM   customers c
LEFT  JOIN orders o
       ON c.customer_id = o.customer_id;

结果

左连接结果

order_id 中的 NULL 表示 Tim Adagala 存在,但尚未下任何订单。

右连接

返回右表的所有记录以及左表中匹配的行(左连接的相反方向)。

右连接示意图

业务问题

显示所有订单及其对应的客户(如果有)。
保留所有订单;如果存在则附加客户信息。

查询

SELECT c.customer_id,
       c.customer_name,
       o.order_id
FROM   customers c
RIGHT  JOIN orders o
       ON c.customer_id = o.customer_id;

结果

右连接结果

全连接

返回两个表的所有记录,无论是否匹配。

全连接示意图

业务问题

显示所有客户和所有订单,包括两侧未匹配的记录。

查询

SELECT c.customer_id,
       c.customer_name,
       o.order_id
FROM   customers c
FULL   OUTER JOIN orders o
       ON c.customer_id = o.customer_id;

输出

结果图片

It looks like the text you provided is just a URL (or part of an image link) rather than translatable content. Could you please share the full passage you’d like translated into Simplified Chinese? Once I have the actual text, I’ll be able to translate it while preserving any source links, formatting, and technical terms as requested.

窗口函数

窗口函数在与当前行相关的一组行上执行计算,不会GROUP BY 子句那样将结果折叠为单行。

窗口函数的语法

function_name(column)
OVER (
    PARTITION BY column   -- optional
    ORDER BY column       -- sometimes required
)
  • OVER() – 定义要操作的行窗口。此子句是必需的。
  • PARTITION BY – (可选)将数据划分为逻辑组。
  • ORDER BY – (有时必需)定义每个分区内行的顺序。以下情况需要它:
    • 排名函数
    • 导航函数
    • 累计总计
0 浏览
Back to Blog

相关文章

阅读更多 »

SQL 连接和窗口函数

SQL 连接和窗口函数 !tonny otieno https://media2.dev.to/dynamic/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uplo...

精通SQL连接和窗口函数

介绍:SQL 连接用于基于相关列合并两个或多个表中的行,而窗口函数在一组行上执行计算,……