I have 2 tables, 1 which holds “total_power” and another which holds “power”
I set it up so that the table with “total_power” simple adds up the “power” for any device connected to that table.
So any foreign key connected to the primary key should tell you what to add.
A better approach is to tell us about the real problem you are trying to solve instead of asking about your attempted approach to solving the real problem. Generally, totals are not stored, they are calculated on the fly as needed. I would need info on what you actually have going on to give you the best answers.
ok, so heres whats going on, I have a devices table, one of its attributes is “power_required”.
I have another table (racks) which can have many devices on it.
I thought id have to create a “total_power” attribute on the racks table to add up the “power_required” for all of its devices, but it would be nice if I can simply do away with the “total_power” attribute and simply do the calculation on the fly. heres the SQL statement to display all the racks
SELECT location, total_power_requirement, elevation, title, power_panel, circuit_breaker, number_of_slots, display, rack_id FROM racks WHERE rack_id > 0
since each device would have a rack_id, how would I alter the SQL so that I can grab the sum of the “power_required” for each rack?
SELECT location, total_power_requirement, elevation, title, power_panel, circuit_breaker, number_of_slots, display, rack_id
FROM racks
LEFT JOIN
(SELECT rack_id, SUM(power_required) AS total_power_requirement FROM devices GROUP BY rack_id)
AS tpr
ON tpr.rack_id = racks.rack_id
WHERE rack_id > 0
SELECT location, elevation, title, power_panel, circuit_breaker, number_of_slots, enabled, rack_id FROM racks LEFT JOIN (SELECT rack_id, SUM(power_requirement) AS total_power_requirement FROM devices GROUP BY rack_id) AS tpr ON tpr.rack_id = racks.rack_id WHERE rack_id > 0 AND enabled = 1 LIMIT 0, 25
MySQL said:
#1052 - Column 'rack_id' in field list is ambiguous
I changed the display attribute to enabled (is that ok?
sorry, yes. With the field in both tables, rack_id becomes ambiguous even though it’s being used as the unifying field. So you’d have to declare rack_id as racks.rack_id in the SELECT and WHERE identifiers.
SELECT location
, elevation
, title
, power_panel
, circuit_breaker
, number_of_slots
, enabled
, racks.rack_id
FROM racks
LEFT JOIN
(SELECT rack_id
, SUM (power_requirement) AS total_power_requirement
FROM devices GROUP BY rack_id) AS tpr
ON tpr.rack_id = racks.rack_id
WHERE racks.rack_id > 0
AND enabled = 1