简体   繁体   中英

Join tables (mysql, php)

I have these tables:

photos (photo_id, photo_title, path)
photos_tags (id, photo_id, tag_id)
tags (tag_id, tag_title). 

On my page I am displaying photos, their titles and I want to show tags for each photo, but I don't know how.

I think I should use LEFT JOIN to join tables photos_tags and tags but I don't know where to start. Any help would be appreciated!

Select 
   photos.photo_title,
   photos.path,
   group_concat(tags.tag_title) as tags
from photos
inner join photos_tags on photos.photo_id = photos_tags.photo_id
inner join tags on tags.tag_id = photos_tags.tag_id
group by photos.photo_id

If you want to get photos without tags as well then you should use left join instead.

If you have a lot of tags or you would like to get more data than tag name then you should prepare 2 queries. Second with in operator containing list of photos ids. So, firstly get all the photos

select * from photos

then get all the ids and pass to second query

select * from tags 
inner join photos_tags on photos_tags.tag_id = tags.tag_id
where photos_tags.photo_id in (1,2,3,4)

You need left joins for all photos with their corresponding tags.

Do like this:

SELECT P.*, T.tag_title FROM photos P
LEFT JOIN photos_tags PT ON P.photo_id = PT.photo_id
LEFT JOIN tags T ON T.tag_id = PT.tag_id

Here you get all the tags, photo id wise.

Let me know for further help.

Assuming you've got your photo id ($yourPhotoId) a query for the specific photo would be something like this:

SELECT t.tag_id, t.tag_title
FROM photo_tags pt
LEFT JOIN tags t ON t.tag_id = pt.tag_id
WHERE pt.photo_id = {$yourPhotoId}

and for all photos(and every columns):

SELECT *
FROM photos p 
LEFT JOIN photo_tags pt ON pt.photo_id = p.photo_id
LEFT JOIN tags t ON t.tag_id = pt.tag_id

Specific Photo would be something like this:

//photo_id just example
$photo_id = '1';
SELECT pt.id as id, pt.photo_id as photo_id, pt.tag_id as tag_id, t.tag_title, p.photo_title, p.path FROM photos p 
INNER JOIN photo_tags pt ON pt.photo_id = $photo_id
INNER JOIN tags t ON t.tag_id = pt.tag_id

All Phosts:

SELECT pt.id as id, pt.photo_id as photo_id, pt.tag_id as tag_id, t.tag_title, p.photo_title, p.path FROM photos p 
INNER JOIN photo_tags pt ON pt.photo_id = p.photo_id
INNER JOIN tags t ON t.tag_id = pt.tag_id

Try this

SELECT P.*, T.tag_title FROM photos P
JOIN photo_tags PT ON P.photo_id = PT.photo_id
LEFT JOIN tags T ON T.tag_id = PT.tag_id
WHERE t.tag_id = 1

SEE DEMO

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