MySQL Forums
Forum List  »  Newbie

Re: Query using AS to get sum of several fields not working
Posted by: Peter Brawley
Date: January 28, 2022 10:20AM

That table design is unfortunately a hack, it needs to be normalised to something like ...

riders( 
  riderid int unsigned primary key auto_increment, 
  ridername varchar(32), 
  ... 
)

ridermiles( 
  rmid unsigned int unsigned primary key auto_increment, 
  rid int unsigned, 
  miles int unsigned, 
  foreign key(rid) references riders(riderid)
)

... after which you query simplifies to ...

select r.riderid, sum(rm.miles) as miles
from riders r
join ridermiles rm on r.riderid=rm.rid
group by riderid
order by riderid;

Till you make that correction, you need to remodel the table every Jan 1, edit such queries to include the new year, and check against each cell containing a null value with, for example, ifnull(y2013,0).

You'll save yourself many such headaches if you take a bit of time to absorb the essentials of relational databases, eg with ...

https://www.artfulsoftware.com/mysqlbook/sampler/mysqled1ch01.pdf

https://www.artfulsoftware.com/dbdesignbasics.html



Edited 1 time(s). Last edit at 01/28/2022 10:55PM by Peter Brawley.

Options: ReplyQuote


Subject
Written By
Posted
Re: Query using AS to get sum of several fields not working
January 28, 2022 10:20AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.