2016-04-16 49 views
1

我有兩個表中的非規範化數據。它是非規範化的,因爲從DepositsAndWithdrawals表(下面第二個)我可以獲得當前客戶的餘額,但爲了快速訪問,我將它保存在UserBalance表(下面的第一個表)中,因此我不需要將所有操作時間:僅在一個SQL查詢中檢測非規範化數據不一致?

 
+----+----------+---------+ 
| 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  | 
+----+------------+---------+ 

這帶來了的情況下有系統競爭條件存在一致性問題。因此,爲了檢測這些數據,我希望每天都有一個檢測平衡不一致的DB查詢(即SUM(amount)balance不同)。如何在單個SQL語句中做這樣的JOIN?

+0

是不是更好的防止了矛盾,而不是嘗試檢測和修復它? –

+0

是的,但這是爲了更好地學習SQL,我想我需要GROUPBY子句,但我不確定 – user1623521

回答

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是您DepositsAndWithdrawals表和AUserBalance