简体   繁体   中英

Aggregating rows into a single new row, plus data from other table

We have two tables of interest in this query.

First off we have a table of music tracks, each with a unique PK and also a FK pointing towards the album that the track belongs to. The second table is this Album table.

So we have around 10 rows of Tracks per 1 row of Album.

I am trying to aggregate all the tracks belonging to one album into one row, plus the album title (which is held in Albums). This is to avoid fiddly PHP code.

At the moment we have:

SELECT Album.Image_URL, Track.Track_Title, Track.Price
FROM Album, Track, Artist
WHERE (Album.Album_ID=Track.Album_ID) AND (Artist.Artist_ID=Track.Artist_ID)
ORDER BY Album.Album_Name ASC

This is one track per row, each with the correct album info. However I'd like of this albums tracks placed into one row.

Appreciate any help, A

The problem is that the number of tracks will vary, so you do not know ahead of time how many columns your result set should return.

If you are willing to accept that the max number of tracks is 10, then it is possible to make an ugly query which will return 10 tracks, and some of them may be NULL if there are less than 10 for a given album.

But you might as well just return one row per album/track combo, and then build your data by iterating through the rows returned.

Cheers,

Daniel

All you need to add is basically GROUP BY Albums.Album_ID :

SELECT Album.Image_URL, Album.Album_Name, SUM(Track.Price) As total_price
FROM Album
JOIN Track ON Album.Album_ID=Track.Album_ID
JOIN Artist ON Artist.Artist_ID=Track.Artist_ID
GROUP BY Albums.Album_ID
ORDER BY Album.Album_Name ASC

I think you need the GROUP_CONCAT() option. So, for one key, group as a comma separated list, all of another... Something like

select 
      Album.ID,  (assuming this column name since not provided)
      Album.Title,
      Album.Image_URL,
      Group_CONCAT( Track.Track_Title ) All_Tracks
  from 
      Album
         join Tracks
            on Album.Album_ID=Track.Album_ID
            join Artist
               onTrack.Artist_ID = Artist.Artist_ID
  group by
      1

If you want to tack the price of each track title, just ad that as part of the GROUP_CONCAT()... Can't confirm syntax, but something like

TRIM( Track.Track_Title + " (" + Track.Price + ")" ) so the concatination might be something like

Album ID   Title       Image Url   AllTracks
1          Some Album  Some URL    First Track ($.99), Second Track, ($1.29), Third Track...

However, isn't the Artist really associated with the ALBUM and not the track? Or are you interested in the Song Writer information... You may need to adjust accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM