仅在一个SQL查询中检测非规范化数据不一致性?

时间:2016-04-16 08:06:06

标签: sql denormalization

我在两个表中有一些非规范化数据。它是非规范化的,因为从DepositsAndWithdrawals表(下面的第二个)我可以获得当前客户的余额,但是为了快速访问我将它保存在UserBalance表中(下面的第一个)所以我不需要将所有的操作总和全部时间:

+----+----------+---------+
| ID | Username | Balance |
+----+----------+---------+
| 1  | Alice    | 50      |
+----+----------+---------+
| 2  | Bob      | 20      |
+----+----------+---------+
| 3  | Charles  | 30      |
+----+----------+---------+
+----+------------+---------+
| ID | CustomerID | Amount  |
+----+------------+---------+
| 1  | 1          | 50      |
+----+------------+---------+
| 2  | 2          | 80      |
+----+------------+---------+
| 3  | 3          | 10      |
+----+------------+---------+
| 4  | 2          | -60     |
+----+------------+---------+
| 5  | 3          | 20      |
+----+------------+---------+

如果系统中存在竞争条件,则会出现一致性问题。因此,为了检测这些,我希望每天都有一个数据库查询来检测平衡不一致性(即SUM(amount)balance不同时)。如何在单个SQL语句中进行这样的JOIN?

1 个答案:

答案 0 :(得分:1)

试试这个

SELECT A.ID As customerId, A.BALANCE, SUM(B.AMOUNT) AS REAL_BALANCE FROM A
 JOIN B on A.ID = B.customerId
GROUP BY A.ID, A.BALANCE
HAVING SUM(B.AMOUNT) <> A.BALANCE

B表是DepositsAndWithdrawalsAUserBalance