Inner join with 3 tables

2019-05-14 02:51发布

问题:

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?

回答1:

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


回答2:

I think this can be resolved using Stored Procedures. Using variables and loops, you can retrieve the records you desire. Getting only a maximum of 5 records from an album is quite challenging when you only use the basic SQL commands. Sometimes, you cannot derive the right records. I suggest you use Stored Proc. :)



回答3:

Try like

"SELECT albums.*,photos.id,photos.path,photo_date as Pht_date
 FROM albums 
     JOIN album_photos 
          ON album_photos.album_id = albums.album_id
     JOIN photos 
          ON photos.photos_id = album_photos_id
"

But you cont give individual limit for photos where it involved in "JOIN" orelse you need to give individually like

$album_ids = "SELECT album_id FROM albums";

then for the photos you need to write query liks

"SELECT photos.* FROM photos 
 WHERE album_photos.album_id in (".$album_ids.") AND album_photos.nick = 'owner'
 JOIN album_photos
 ON album_photos.photo_id = photos.photos_id 
 LIMIT 0,10
 "