Reputation: 3288
I'm building a virtual currency system, and as it is situated in real money, accurate retention of data is a very key goal. I am building my currency so that user wallets do not have a fixed value (an 'amount'), rather, they are the net of all transactions to and from that wallet -- sort of like bitcoin.
So, if I'm calculating the amount of a wallet, my MySQL query looks like this.
SELECT (
SELECT IFNULL(SUM(`tx`.`amount`), 0)
FROM `transactions` AS `tx`
WHERE `tx`.`to_wallet_id` = 5
) - (
SELECT IFNULL(SUM(`tx`.`amount`), 0)
FROM `transactions` AS `tx`
WHERE `tx`.`from_wallet_id` = 5
) AS `net`
This query builds a net
value using the aggregate data of a SUM()
for all transactions towards a wallet subtracted by all transactions from a wallet. The final value represents how much money the wallet currently contains.
In short, I want to know how I can optimize my table so that these queries are very fast and scale as well possible.
I would assume I should index [from_wallet_id, amount]
and [to_wallet_id, amount]
, but I'm very uncertain.
Upvotes: 1
Views: 58
Reputation: 1442
I would suggest to do the following:
[from_wallet_id, amount]
and [to_wallet_id, amount]
). At allows to run queries which retrieves all necessary data from indexes. If it doesn't help, you can think about the following options:
Upvotes: 1