I have a simple one-to-many relationship. One table is a list of albums, and the other a list of photos. Each photo can only be of one album, but an album contains many images.
Now I want to get a list of all the albums in a single query. The information I want is some values of the album itself (let's say the name
of the album), the total image count in that album and some values of the first image.
I already have the total image count and the album name, but I am having some issues trying to get the first image values as well.
SELECT albums.id, albums.name, COUNT(photos.id) AS imageCount
FROM albums
LEFT JOIN photos ON albums.id = photos.albumid
GROUP BY name
ORDER BY id DESC
I have tried several approaches from other answers but I seem to be doing something wrong. It's especially confusing since I am using COUNT()
as well.
I have created a sqlfiddle that has this query in it as well as a small sample database. So how do I also get some values of the first element of photos?