查询数据库中的更新记录
Query updated records in Database
目前我们所有的表都有 created_at
和 updated_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 关系的更新,例如 CartItems
s 和 User
s。
有没有一个很好的方法来处理这个问题,以便我们得到所有直接或间接(通过 FK 关系)更新的 Cart
?
您可以使用 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') ;
目前我们所有的表都有 created_at
和 updated_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 关系的更新,例如 CartItems
s 和 User
s。
有没有一个很好的方法来处理这个问题,以便我们得到所有直接或间接(通过 FK 关系)更新的 Cart
?
您可以使用 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') ;