How would you accomplish this task to get best performance?
Table schema:
CREATE TABLE `test_truck_report` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`truck_id` INT(11) NOT NULL,
`odometer_initial` INT(11) NOT NULL,
`odometer_final` INT(11) NOT NULL,
`fuel_initial` INT(11) NOT NULL,
`fuel_final` INT(11) NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB;
What i'm trying to execute is this query:
SELECT
truck_id,
(odometer_final - odometer_initial) AS mileage,
(fuel_initial - fuel_final) AS consumed_fuel,
(consumed_fuel / mileage) AS consumption_per_km
FROM
test_truck_report
WHERE
consumption_per_km > 2
Somehow this obvious on the first sight logic doesn't work and i'm forced to use this query instead:
SELECT
truck_id,
(odometer_final - odometer_initial) AS mileage,
(fuel_initial - fuel_final) AS consumed_fuel,
((fuel_initial - fuel_final) / (odometer_final - odometer_initial)) AS consumption_per_km
FROM
test_truck_report
WHERE
((fuel_initial - fuel_final) / (odometer_final - odometer_initial)) > 2
I assume that constant recalculation of each calculated field every time where it needs to be placed makes significant performance downgrade. And this is just a test case, actual working table has 50+ fields and some of calculated fields consists of 10+ operands. So it's a really HUGE problem at the moment.
Reason why i don't want to actually create these fields and perform something like:
UPDATE
`test_truck_report`
SET
consumed_fuel = fuel_initial - fuel_final
is that existing records are being constantly updated by the users and in that case i would need to constantly update that data. So do you consider creating actual fields a better idea? Or is there some better way?
Thanks.