简体   繁体   English

查询数据库中的更新记录

[英]Query updated records in Database

Currently all our tables have a created_at and updated_at timestamp, eg目前我们所有的表都有一个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)   |

The updated_at field is modified with every INSERT. updated_at字段随每个 INSERT 被修改。

This allows us to query all Cart 's which have been updated since a particular point in time with something like this:这允许我们查询自特定时间点以来已更新的所有Cart ,如下所示:

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

However this would not capture updates to FK relationships such as CartItems s and User s.但是,这不会捕获 FK 关系的更新,例如CartItemsUser

Is there a nice way to handle this so that we get all Cart s which have either directly or indirectly (via FK relationships) been updated?有没有一种很好的方法来处理这个问题,以便我们获得所有直接或间接(通过 FK 关系)更新的Cart

You can use exists :您可以使用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') ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM