Question

I'm trying to get data from three tables (photos, albums, album_photos), then the program searches a user's albums in the album table, then look for every album the ID's of the photos in album_photos, and then, for each ID, look at the photos table all data by ID.

Yesterday I asked something like this: Inner join with 3 tables, but now, I think the question is different, I'm wondering how I can add a limit to a request by inner join.

So, I'm working now in this code:

SELECT a.album_name, a.album_id, c.* 
FROM albums a
INNER JOIN album_photos b ON a.album_id = b.album_id
INNER JOIN photos c ON b.photo_id = c.photo_id
WHERE (
  SELECT COUNT(*) 
  FROM album_photos d
  WHERE b.album_id = d.album_id
  AND d.nick =  :nick
) <=5

Ok, this code select's the albums that have 5 or less photos. I do not want the code to do that, no matter how many photos have the album, I want to show the album with a LIMIT OF 5 photos.

Other people have told me that you can not do it, I believe that this is not so, because the SQL language is very complex and I think we should have the tool to do it.

Is there any way to do this in a proper way?

*In the link that I'm shared above I put an example about the output data.

Was it helpful?

Solution

Try changing the where clause to this:

WHERE (
  SELECT COUNT(*) 
  FROM album_photos d
  WHERE d.album_id = b.album_id and
        d.photo_id <= b.photo_id
  AND d.nick =  :nick
) <= 5

This counts the number of photos in order, not just the number of photos in the album.

OTHER TIPS

Since album_photos has a mapping relationship between photos and albumns, you can specify the number of photos to join on by using TOP:

SELECT a.album_name, a.album_id, p.* 
FROM albums a
INNER JOIN album_photos ap ON 
   ap.photo_id = (select top 5 photo_id from album_photos where a.album_id = ap.album_id order by photo_id)
INNER JOIN photos p ON ap.photo_id = p.photo_id

The Order by photo_id in the subquery will ensure the same 5 (or fewer) photos are returned

EDIT PER COMMENT. Modifying to use MySql LIMIT instead of T-SQL TOP

SELECT a.album_name, a.album_id, p.* 
FROM albums a
INNER JOIN album_photos ap ON 
   ap.photo_id = (select photo_id from album_photos where a.album_id = ap.album_id order by photo_id LIMIT 0, 5)
INNER JOIN photos p ON ap.photo_id = p.photo_id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top