【发布时间】:2020-11-07 00:19:07
【问题描述】:
我需要知道 mysql 查询中的逻辑以跟踪所有更改的历史记录。下面的例子将解释我的期望。
account表
+------+---------+---------------------+---------------------+
| id | emailid | created_date | modified_date |
+------+---------+---------------------+---------------------+
| 1 | abc | 2020-03-20 00:00:00 | 2020-07-10 00:00:00 |
+------+---------+---------------------+---------------------+
account_history表
+------+---------+---------------------+
| id | emailid | modified_date |
+------+---------+---------------------+
| 1 | def | 2020-04-03 00:00:00 |
| 1 | ghi | 2020-05-05 00:00:00 |
| 1 | lmn | 2020-06-05 00:00:00 |
| 1 | opq | 2020-07-01 00:00:00 |
| 1 | opq | 2020-07-03 00:00:00 |
| 1 | qrs | 2020-07-10 00:00:00 |
+------+---------+---------------------+
预期结果
+------+-----------+----------+----------+-------------------+---------------------+
| id | parameter | oldvalue | newvalue | event | event_datetime |
+------+-----------+----------+----------+-------------------+---------------------+
| 1 | emailid | NULL | def | New Entry | 2020-03-20 00:00:00 |
| 1 | emailid | def | ghi | Change in account | 2020-04-03 00:00:00 |
| 1 | emailid | ghi | lmn | Change in account | 2020-05-05 00:00:00 |
| 1 | emailid | lmn | opq | Change in account | 2020-06-05 00:00:00 |
| 1 | emailid | opq | qrs | Change in account | 2020-07-03 00:00:00 |
| 1 | emailid | qrs | abc | Change in account | 2020-07-10 00:00:00 |
+------+-----------+----------+----------+-------------------+---------------------+
我有名为account 的主表和名为account_history 的历史表。帐户的每次更改都将在其历史表中进行跟踪,当前值将存储在历史表中。我期待我的输出是这样的。如果没有发生变化,则无需跟踪。我每天都有逻辑要跟踪。但我想跟踪过去的数据。
跟踪每日查询,
mysql> select id,'emailid',acch.emailid as oldvalue,acc.emailid as newvalue,'Change in account',acc.modified_date from account acc join account_history acch using(id) where acc.emailid!=acch.emailid and acc.modified_date=acch.modified_date;
+------+---------+----------+----------+-------------------+---------------------+
| id | emailid | oldvalue | newvalue | Change in account | modified_date |
+------+---------+----------+----------+-------------------+---------------------+
| 1 | emailid | qrs | abc | Change in account | 2020-07-10 00:00:00 |
+------+---------+----------+----------+-------------------+---------------------+
1 row in set (0.00 sec)
感觉难以跟踪过去的数据。帮我解决这个问题。
mysql Ver 14.14 Distrib 5.7.23
即使超过 1 或 2 个查询来得出解决方案也会很有帮助。通过创建任何中间表并得出解决方案会很有帮助。
【问题讨论】:
-
了解您正在使用的 mysql 版本会很有帮助。
-
mysql Ver 14.14 Distrib 5.7.23
-
account中
modified_date的值早于account_history的最后一次更改? -
抱歉,打错了。会更新的
-
我不明白为什么 def 的活动日期是 03-20 而实际上似乎是 04-03
标签: mysql mysql-workbench mysql-python