Question

I have three tables:

 pindex_photos:        pindex_names:    pindex_link:
 | id  | filename  |   | id | name  |   | photo_id | name_id |
 |-----|-----------|   |----|-------|   |----------|---------|
 | 1   | DSC1.jpg  |   | 1  | Leo   |   | 1        | 3       |
 | 2   | DSC2.jpg  |   | 2  | Liz   |   | 1        | 2       |
 | 3   | DSC5.jpg  |   | 3  | Tom   |   | 3        | 1       |
 | ..  | ..        |   | .. | ..    |   | 2        | 1       |
                                        | ..       | ..      |

In pindex_link the two first tables relate together with their id. Now I would like to make a Report File From this Tables like:

 Report on Images (list only Images that have > 0 connections to names)
 DSC1.jpg (2): Liz, Tom
 DSC2.jpg (1): Leo
 ..

 Report on Names (list only Names that have > 0 connections to images)
 Leo (2): DSC2.jpg, DSC5.jpg
 Liz (1): DSC1.jpg
 ..

Can me anyone give me help or a clue how to achieve this?

Was it helpful?

Solution

select p.filename, group_concat(n.name)
from pindex_photos p
left join pindex_link l on l.photo_id = p.id
left join pindex_names n on l.name_id = n.id
group by p.filename

and

select n.name, group_concat(p.filename)
from pindex_photos p
left join pindex_link l on l.photo_id = p.id
left join pindex_names n on l.name_id = n.id
group by n.name

OTHER TIPS

Report on Images:

SELECT p.id,COUNT(pn.name) as Count,group_concat(pn.name)
FROM pindex_link pl LEFT JOIN
pindex_photos p on p.id=pl.photo_id INNER JOIN
pindex_names pn on pn.id=pl.name_id
GROUP BY p.id

Result:

ID  COUNT   GROUP_CONCAT(PN.NAME)
1   2       Liz,Tom
2   1       Leo
3   1       Leo

See result in SQL Fiddle.

Report on Names:

SELECT pn.name,COUNT(p.filename) as Count,group_concat(p.filename)
FROM pindex_link pl LEFT JOIN
pindex_photos p on p.id=pl.photo_id INNER JOIN
pindex_names pn on pn.id=pl.name_id
GROUP BY pn.name

Result:

NAME    COUNT   GROUP_CONCAT(P.FILENAME)
Leo     2       DSC5.jpg,DSC2.jpg
Liz     1       DSC1.jpg
Tom     1       DSC1.jpg

See result in SQL Fiddle.

if you want the output formatted into a single column:

SELECT 'Report on Images (list only Images that have > 0 connections to names)';
SELECT concat(filename, ' (', COUNT(pn.name), '): ', group_concat(pn.name)) as fixed_output  
FROM pindex_link pl LEFT JOIN
pindex_photos p on p.id=pl.photo_id INNER JOIN
pindex_names pn on pn.id=pl.name_id
GROUP BY p.id;

SELECT 'Report on Names (list only Names that have > 0 connections to images)';
SELECT concat(pn.name, ' (' , COUNT(p.filename), '): ',  group_concat(p.filename)) as fixed_output
FROM pindex_link pl LEFT JOIN
pindex_photos p on p.id=pl.photo_id INNER JOIN
pindex_names pn on pn.id=pl.name_id
GROUP BY pn.name;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top