Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner join with 3 tables

I'm working with PHP and PDO, and I need to recolect information joining 3 tables:

  • photos
  • albums
  • album_photos

The table have the following structure:

photos:

photo_id  (int)
path      (varchar)
nick      (varchar)
date      (timestamp)

albums

album_id   (int)
album_name (varchar)
nick       (varchar)
date       (timestamp)

album_photos

album_id (int)
photo_id (int)
nick     (varchar)
date     (timestamp)

So, I want to show all the albums with a max of 5 photos for each one, where the user nick is 'owner'.

To be shown as follows:

album_name_1:
[photo_1]
[photo_2]
[photo_3]
[photo_4]
[photo_5]

album_name_2:
[photo_1]
[photo_2]
[photo_3]
[photo_4]
[photo_5]

I only know that something like this can be made with INNER JOIN, but I can't found how I can make it with 3 tables.

There examples or other help that I can get to do this?

like image 409
Tomás Juárez Avatar asked Feb 02 '26 05:02

Tomás Juárez


1 Answers

SELECT  a.*, c.date
FROM    Album a
        INNER JOIN Album_Photo b
            ON a.Album_ID = b.Album_ID
        INNER JOIN Photo c
            ON b.Photo_ID = c.Photo_ID
WHERE   c.Nick = 'owner' AND
        (
          SELECT COUNT(*) 
          FROM   album_photo d
          WHERE  b.album_id = d.album_id AND
                 d.nick = 'owner' AND
                 b.date >= d.date
        ) <= 2   // <<== change this value to 5
  • SQLFiddle Demo
like image 189
John Woo Avatar answered Feb 03 '26 19:02

John Woo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!