I have these three tables:
CREATE TABLE `projects` (
`project_id` int(11) NOT NULL AUTO_INCREMENT,
`status` varchar(50) NOT NULL DEFAULT '',
`work_performed` longtext,
`original_amount` decimal(10,2) DEFAULT '0.00',
PRIMARY KEY (`project_id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=latin1;
CREATE TABLE `project_additional` (
`additional_id` int(11) NOT NULL AUTO_INCREMENT,
`project_id` int(11) NOT NULL,
`selected` int(1) NOT NULL DEFAULT '0',
`additional_description` longtext NOT NULL,
`quantity` int(11) DEFAULT NULL,
`unit_measurement` varchar(5) DEFAULT NULL,
`unit_cost` decimal(10,2) NOT NULL DEFAULT '0.00',
`extended_price` decimal(10,2) NOT NULL DEFAULT '0.00',
PRIMARY KEY (`additional_id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=latin1;
CREATE TABLE `invoice_transactions` (
`transaction_id` int(11) NOT NULL AUTO_INCREMENT,
`project_id` int(11) DEFAULT NULL,
`transaction_date_time` datetime DEFAULT '0000-00-00 00:00:00',
`transaction_type` varchar(50) DEFAULT NULL,
`transaction_amount` decimal(10,2) NOT NULL DEFAULT '0.00',
`transaction_memo` varchar(255) DEFAULT NULL,
PRIMARY KEY (`transaction_id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=latin1;
What I am attempting to do is get the total still due for ALL projects with a specific status. The projects table holds the "original_amount" of the project and defines the status of the project, the project_additional table holds all additional items for the project and the prices of those items, the invoice_transactions table well.... holds all the invoice transactions.
Here is what needs to happen...
1: Get the total of the "original_amounts" for all projects with a status of "foo".
2: Get the total of all the extended_prices from the project_additional table for the items that have been selected for these projects (project_additional.selected=1 or yes).
3: Get the total of all transactions for each transaction_type (payments, credits and charges) for these projects.
4: Display the total still due for all these projects after this formula has been applied:
projects.original_amount+project_additional.extended_price(for all selected items)+invoice_transactions.transaction_amount(charges)-invoice_transactions.transaction_amount(credits)-invoice_transactions.transaction_amount(payments)
Note: in the formula above I show project_additional.extended_price(for all selected items), invoice_transactions.transaction_amount(charges), invoice_transactions.transaction_amount(credits) and invoice_transactions.transaction_amount(payments). I realize that I am misusing the () part, what I am trying to show is what types of transaction_type exist and that it needs to include all selected items from project_additional.
I am capable of doing this on a single specific record but am at a complete loss on how to do this for all projects of a certain status (status=foo). I'm looking for a MySQL ninja for sure!