0

I have three tables:

Photos:

  • photo_id
  • photo_name

Photo_to_category

  • id
  • photo_id
  • category_id

Category

  • category_id
  • category_name

I would like show all photo with category. One photo can have eg.. 5 category. Someone can get me a full SQL request? I try with LEFT JOIN but it not working too well. Maybe GROUP()?? Thanks

// MY CODE

SELECT * FROM photos AS p
LEFT JOIN photo_to_category AS ptc ON p.photo_id = ptc.photo_id
LEFT JOIN category AS c ON ptc.category_id = c.category_id
Kamilos
  • 39
  • 1
  • 7

1 Answers1

0

You have to use GROUP_CONCAT to generate a string that contains all categories of a photo, and group your results by photo id.

See this question for more information: How to use GROUP BY to concatenate strings in MySQL?

Community
  • 1
  • 1
Fabien Warniez
  • 2,731
  • 1
  • 21
  • 30
  • I have another question :) I would like to get all the photos from the category and display a rest category (eg a picture of the city may be in the category of the night, the city, people) Should I get a picture and categories. WHERE c.category_id = 14 / / does not work, I get the photo but without the rest of the category – Kamilos Jan 21 '14 at 23:14
  • You need to join the category table and the joint table twice (under different names). One is used to filter (the WHERE), one is used to retrieve the categories to the images. – Fabien Warniez Jan 21 '14 at 23:19
  • Can you get me example? – Kamilos Jan 21 '14 at 23:26
  • LEFT JOIN the join table twice (ie. copy paste the line you have and change the alias to ptc2). Then use ptc2 to filter (in the WHERE). – Fabien Warniez Jan 21 '14 at 23:28