http://qs321.pair.com?node_id=799116

Jazz has asked for the wisdom of the Perl Monks concerning the following question:

I'm sorry, but this is more of a MySQL question than a perl one. I'd appreciate any pointers or suggestions, though.

First, the query:

my $sth = $dbh->prepare( "SELECT * FROM Images LEFT JOIN Regio ON Images.RegioID = Regio.RegioID LEFT JOIN Insula ON Images.InsulaID = Insula.InsulaID LEFT JOIN ImgThemes ON Images.ImageID = ImgThemes.ImageID LEFT JOIN Sources ON Images.SourceID = Sources.SourceID ORDER BY ImageName LIMIT $start,$numrows" );

Now, a simplified version of the table structure:

------- --------- ---------- Regio Images ImgThemes ------- --------- ---------- RegioID >--| ImageID >----< ImageID RegioName |--> RegioID ThemeID <----| ImageName | ------- |--> InsulaID ---------- | Insula | RoomID (etc) Themes | ------- | SourcesID >-| ---------- | InsulaID >-| | ThemeID >----| InsulaName --------- | ThemeName Sources | ThemeCategoryID <-| --------- | | SourceID <--| ---------- | SourceName ThemeCategories | Publishers ---------- | PublishYear ThemeCategoryID >-| CategoryName

The problem is that this yields Cartesian results, creating duplicate values for Image records when there's no match in the Images table for values in the joined ones.

For most of the join tables, the correct value always yields a single result (the name); for "ImgThemes", multiple values are most common. Not every Image is required ImgThemes, but not Regio or Insula.

What is the correct syntax to ensure all images are returned, but not duplicated? This is my first excursion into non-"natural" joins, and the goal is to retrieve each respective name in each of the tables without having to perform separate queries.

Thank you for any help you may be able to offer.