# 连续行比较

在本教程中，我们将介绍如何使用自连接技术来比较同一个表中的连续行。

假设您有一个名为`inventory`的表，其中包含由[CREATE TABLE](http://www.yiibai.com/mysql/create-table.html)语句定义的结构，如下所示：

```sql
USE testdb;
CREATE TABLE inventory(
  id INT AUTO_INCREMENT PRIMARY KEY,
  counted_date date NOT NULL,
  item_no VARCHAR(20) NOT NULL,
  qty int(11) NOT NULL
);
```

在库存(`inventory`)表中：

* `id`是自动增量列。
* `count_date`是计数日期。
* `item_no`是发布到广告资源的商品代码。
* `qty`是库存中累计的现货数量。

以下是`inventory`表的示例数据：

```sql
INSERT INTO inventory(counted_date,item_no,qty)
VALUES ('2017-10-01','A',20),
    ('2017-10-01','A',30),
    ('2017-10-01','A',45),
    ('2017-10-01','A',80),
    ('2017-10-01','A',100);
```

如果想知道每个物品每天收到的物品数量，需要将特定日期的现有数量与前一天进行比较。

换句话说，在`inventory`表中，需要将一行与其连续行进行比较以找出差异。

在MySQL中，可以使用[自连接技术](http://www.yiibai.com/mysql/self-join.html)来比较连续的行，如以下查询：

```sql
SELECT 
    g1.item_no,
    g1.counted_date from_date,
    g2.counted_date to_date,
    (g2.qty - g1.qty) AS receipt_qty
FROM
    inventory g1
        INNER JOIN
    inventory g2 ON g2.id = g1.id + 1
WHERE
    g1.item_no = 'A';
```

执行上面查询语句，得到以下结果 -

```sql
+---------+------------+------------+-------------+
| item_no | from_date  | to_date    | receipt_qty |
+---------+------------+------------+-------------+
| A       | 2017-10-01 | 2017-10-01 |          10 |
| A       | 2017-10-01 | 2017-10-01 |          15 |
| A       | 2017-10-01 | 2017-10-01 |          35 |
| A       | 2017-10-01 | 2017-10-01 |          20 |
+---------+------------+------------+-------------+
4 rows in set
```

[INNER JOIN](http://www.yiibai.com/mysql/inner-join.html)子句`g2.id = g1.id + 1`中的条件允许您将当前行与`inventory`表中的下一行进行比较，当然，假设`id`列中没有间隙。

如果无法避免差距，您可以创建一个附加列，例如`seq`来维护行的顺序，以便应用此技术。

在本教程中，您已经学会了如何使用自连接技术来比较同一个表中的连续行。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hezhiqiang-book.gitbook.io/mysql/di-er-zhang/lian-xu-hang-bi-jiao.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
