Xorii
Xorii

Reputation: 323

Mysql multiple join between two tables

I have got two tables. One is for news and second one for images. Each news can have 0-3 images (image_1, image_2, image_3 in table news - its id). Now iam trying to get all rows from images table but its giving me back only one.

Like that (but it is not working)

select news.id as nid, image_1, image_2, image_3, photos.id as pid, big, small
from news
left join photos
on image_1=photos.id, image_2=photos.id, image_3=photos.id
order by nid desc

Upvotes: 0

Views: 38

Answers (2)

juergen d
juergen d

Reputation: 204924

You have to join the photos table 3 times with different aliases.

But you actually should rather change your table design. Add another table called news_photos

news_photos table
-----------------
news_id
photo_id

Then you can remove the image columns from the news table.

After the changes you can select news with all photos of like that

select n.*, p.name
from news
left join news_photos np on n.id = np.news_id
left join photos p on p.id = np.photo_id
where n.id = 1234

Upvotes: 0

Zafar Malik
Zafar Malik

Reputation: 6854

Even @juergen has suggested better option and also guided you how to solve your problem in your way but if stil you are facing issue how to do then you can follow below query-

SELECT p.id AS pid, n1.image_1, n2.image_2, n3.image_3, big, small
FROM photos AS p
LEFT JOIN news AS n1 ON n1.image_1=p.id 
LEFT JOIN news AS n2 ON n2.image_2=p.id 
LEFT JOIN news AS n3 ON n1.image_3=p.id 
ORDER BY n.id DESC;

Upvotes: 1

Related Questions