Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I want to select 3 columns from 3 different tables that are joined together.

I have an albums table that has albumid, genreid and name, and a genre table has genreid and name and Ive joined them together as follows:

SQL
SELECT a.albumid, a.name, g.name as genrename
FROM albums a
JOIN genre g
ON a.genreid=g.genreid
ORDER BY a.name;


However, I have another table called tracks that contains the tracks linked with their respective album (linked by albumid which is present in both tables). in the tracks table each track has a duration for the song.

What I am trying to achieve is, with the SQL I already have, I would like to get a sum of all the track durations added together to get a total for that album, which can then be displayed as album duration.

Something like this, but with some kind of subquery to calculate album duration:

SQL
SELECT a.albumid, a.name, g.name as genrename
FROM albums a
JOIN genre g
ON a.genreid=g.genreid
JOIN tracks t
ON a.albumid=t.albumid
ORDER BY a.name;
Posted
Updated 28-Apr-15 9:53am
v2
Comments
Sascha Lefèvre 28-Apr-15 16:04pm    
Oh hey, just realized it's you - no PHP today ;-)
jba1991 29-Apr-15 8:34am    
Haha no not today :P

1 solution

This should work, you would just have to adjust the column name tracks.duration if it's different:

SQL
SELECT a.albumid, a.name, g.name as genrename, sum(t.duration) as albumduration
FROM albums a
JOIN genre g
ON a.genreid=g.genreid
JOIN tracks t
ON a.albumid=t.albumid
GROUP BY a.albumid, a.name, g.name
ORDER BY a.name;
 
Share this answer
 
Comments
jba1991 29-Apr-15 8:34am    
Correct as always. Thanks :)
Sascha Lefèvre 29-Apr-15 8:43am    
You're welcome! :)
jba1991 29-Apr-15 13:41pm    
How could I convert sum(t.duration) into HH:MM:SS from seconds inside SQL? is that possible?
Sascha Lefèvre 29-Apr-15 13:42pm    
In MySQL yes?
jba1991 29-Apr-15 13:48pm    
well SQLite

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900