具有自动覆盖功能的SQL Book页面索引

时间:2018-11-20 15:14:35

标签: sql postgresql typescript typeorm

我想实现类似 Book pages 的功能。

例如: 我有一本书有100页,每页都有唯一的优先级/页码(1-100)。

+-----+--------------------------------+------+
| id  |            content             | page |
+-----+--------------------------------+------+
| 1   | cover                          | 1    |
| 2   | prelude                        | 2    |
| ... | ...                            | ...  |
| 50  | and so he do rig a jig jig...  | 50   |
| 51  | and he come to the bus stop... | 51   |
| ... | ...                            | ...  |
| 100 | back-cover                     | 100  |
+-----+--------------------------------+------+

假设我在页面5051之间插入了一个新页面。因此,插入的页面优先级/页面号为51

因此,覆盖上面的页码,“旧”页面51-100将是52-101。

+-----+--------------------------------+------+
| id  |            content             | page |
+-----+--------------------------------+------+
| 1   | cover                          | 1    |
| 2   | prelude                        | 2    |
| ... | ...                            | ...  |
| 50  | and so he do rig a jig jig...  | 50   |
| 101 | this is a new page             | 51   |
| 51  | and he come to the bus stop... | 52   |
| ... | ...                            | ...  |
| 100 | back-cover                     | 101  |
+-----+--------------------------------+------+

我正在使用PostgreSQL,TypeORM,TypeScript。

1 个答案:

答案 0 :(得分:1)

--Updates the table and sets each page value to itself + 1
--Under conditions: the page number is the same as the inserted record but the
--content is different (the original record with that page number)
--Or the page number is greater than the page number of the inserted record    
UPDATE Table
SET [page] = [page] + 1
WHERE ([page] >= insertedPageNumber AND content <> insertedPageContent) OR [page] > insertedPageNumber