1

I have two tables images2 and image_data

enter image description here enter image description here

So the goal is to have 1 table for ALL the image uploads (images2) and then the image_data is to assign that image with different options.

So for example, here is some sample data:

enter image description here

So image_id 10 has more than one row, because this image is associated with both TN and CQ. And they could also be associated with more than one language and slide, so I would add on to the second row and change slide_id or language_id .. if wanted to add more, than I would add a new row for it.

The goal is to have a list of all the images, and then when you click on it it pops up and you can edit the options and change it straight from there.

enter image description here

I need help writing a query. The one I have right now:

SELECT images2.id, images2.filename, image_data.slide_id, image_data.language_id,
image_data.type FROM images2 
LEFT JOIN image_data ON images2.id = image_data.image_id

A couple things wrong with that query.. It is showing the duplicates, because image_id 10 has two rows.

enter image description here

But I need that second row of image #10 because I need to see that it is also associated with CQ so I can check the checkbox when it pops up.

So I need to create a query to show ALL the unique images no duplicates, with all of the options it has.

I'm not sure the best way to do this.. do I need to re-do the way my database tables are? Any help is appreciated.

Thanks.

4

2 回答 2

2

What you could do is use GROUP_CONCAT() to turn values in multiple rows into a single concatenated string. The following retrieves the ids of slides and languages as well as their names to better facilitate your form.

SELECT
    a.id,
    a.filename,
    GROUP_CONCAT(CONCAT(b.slide_id, '::', c.slide_name)) AS slides,
    GROUP_CONCAT(CONCAT(b.language_id, '::', d.language_name)) AS languages,
    GROUP_CONCAT(b.type) AS types,
FROM 
    images a
LEFT JOIN
    image_data b ON a.id = b.image_id
LEFT JOIN 
    slides c ON b.slide_id = c.id
LEFT JOIN
    languages d ON c.language_id = d.id
GROUP BY
    a.id

Your result set for image 10 will look something like:

id    |    image_filename    |    slides    |    languages    |    types
-------------------------------------------------------------------------
10    |    p170sfhe...       |    5::slide5 |    1::language1 |    TN,CQ

In php, just explode() the strings based on the delimiters.

于 2012-06-30T18:06:28.050 回答
1

you could use GROUP_CONCAT to get a csv of the fields:

SELECT
  images2.id,
  images2.filename,
  GROUP_CONCAT(DISTINCT image_data.slide_id) AS slides,
  GROUP_CONCAT(DISTINCT image_data.language_id) AS langs,
  GROUP_CONCAT(DISTINCT image_data.type) AS types
FROM images2 
LEFT JOIN image_data ON (images2.id = image_data.image_id)
GROUP BY images2.id
于 2012-06-30T18:04:58.613 回答