【问题标题】:Query updated records in Database查询数据库中更新的记录
【发布时间】:2020-10-10 00:54:54
【问题描述】:

目前我们所有的表都有created_atupdated_at 时间戳,例如

Cart

| ID | created_at | updated_at | user_id |
|----|------------|------------|---------|
| 1  | 2020-06-15 | 2020-06-15 | 6       |
| 2  | 2020-06-16 | 2020-06-16 | 7       |


CartItem

| ID | created_at | updated_at | qty     | cart_id |
|----|------------|------------|---------|---------|
| 3  | 2020-06-15 | 2020-06-16 | 2       | 1       |
| 4  | 2020-06-16 | 2020-06-18 | 1       | 1       |
| 5  | 2020-06-16 | 2020-06-18 | 6       | 2       |

User

| ID | created_at | updated_at | name                      |
|----|------------|------------|---------------------------|
| 6  | 2020-05-01 | 2020-06-19 | Lance                     |
| 7  | 2020-05-01 | 2020-05-01 | Barry (from Eastenders)   |

updated_at 字段会随着每次 INSERT 进行修改。

这使我们可以查询自特定时间点以来已更新的所有Cart,如下所示:

SELECT * FROM Cart WHERE updated_at > 2020-06-15

但是,这不会捕获 FK 关系的更新,例如 CartItemss 和 Users。

有没有一种很好的方法来处理这个问题,以便我们获得所有直接或间接(通过 FK 关系)更新的 Carts?

【问题讨论】:

    标签: sql database postgresql database-design database-schema


    【解决方案1】:

    你可以使用exists:

    select c.*
    from cart c
    where c.updated_at > '2020-06-16' or
          exists (select 1 from cartitem ci where ci.cart_id = c.cart_id and ci.updated_at > '2020-06-16') or
          exists (select 1 from user u where u.user_id = c.user_id and u.updated_at > '2020-06-16') ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      • 2016-01-15
      相关资源
      最近更新 更多