2

I have a table containing the balances of about 100 accounts (it's variable). One record per account. The balances are continually updated but I would like to find the best way to archive the current balance each day.

I'm looking for the most efficient way to do this.

Table schemas:

-- --------------------------------------------------------
--
-- Table structure for table `acc_bals`
--
-- Holds the tracks the balances of all coa's and bank accounts
CREATE TABLE IF NOT EXISTS `acc_bals` (
    `id` INT(11) NOT NULL auto_increment,
    `acc_type` TINYINT(4) NOT NULL comment '1 - coa; 2 - bank accounts',
    `acc_id` SMALLINT(5) NOT NULL,
    `acct_balance` VARBINARY(40) NOT NULL,
    PRIMARY KEY (id)
)  engine=InnoDB DEFAULT charset=utf8 auto_increment=1;

--
-- Table structure for table `balance_archive`
--
CREATE TABLE IF NOT EXISTS `balance_archive` (
  `id` mediumint(6) unsigned NOT NULL AUTO_INCREMENT,
  `date` date NOT NULL COMMENT 'Beginning of the day for which this value was archived for..',
  `coa_id` smallint(4) unsigned NOT NULL COMMENT 'Foreign ID of COA.',
  `bal` varbinary(27) NOT NULL COMMENT 'Archived COA balance at beginning of specified date.',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

The reason for the varbinary columns is because the balances are encrypted.

I was originally thinking to query acc_bals and put all the account id's and values into an array, having decrypted the values, and then run a second query and for each item in the array, copy it into the archive table.

It then occurred to me that I probably do not need to decrypt the values at all which would save a lot of processing and then further more, it might be possible to do this in a single query?

If my approach seems right, perhaps someone can suggest how that query might look please?

I'm using MySQL PDO.

1 Answer 1

3

Simple select into will do in a recurring event set for each day. Something like :

insert into balance_archive (date,coa_id,bal)
select now(),ab.id,ab.acct_balance
from acc_bals ab

That way you don't need to use PHP at all, you can do it with MySql only.

2
  • Thanks Eric. I'm getting "#1327 - Undeclared variable: balance_archive" though. Any ideas what I'm doing wrong when running the query? It seems to think that the recipient table name is a variable rather than a table name. I tried putting it in back-ticks but no avail. May 6, 2013 at 7:34
  • @PeterSnow I've corrected the query, I think that's the syntax for MySQL May 6, 2013 at 7:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.