2009-08-09 5 views
2

J'ai 2 tables:enregistrements dans un 1 Tri: n (one-to-many) relation

+-----------+ +------------------------------------+--------------+ 
+ persons | | photos           | 
+-----------| +---------------------------------------------------+ 
+ id | name + | id | person_id | path    | title  | 
+-----------+ +---------------------------------------------------+ 
+ 1 | Tom + | 1 |   2 | ~fred/me.png  | Yo, it's Me! | 
+ 2 | Fred + | 2 |   2 | ~fred/my_wife.png | I'm Susan | 
+ 3 | Jack + | 3 |   1 | ~tom/my_dog.jpg | a woof  | 
+-----------+ +---------------------------------------------------+ 

qui a sont dans cette relation:

Personne hasMany photo < - > Photo appartient à la personne

Je voudrais lister toutes les personnes avec leurs photos (même si quelqu'un n'en a pas, comme Jack) et les classer par titre de photos.

Quelle requête SQL (MySQL) dois-je écrire pour cela? Puis-je utiliser des jointures dans une relation un-à-plusieurs?

PS: Tout comme une information, je voudrais être en mesure de construire un tel tableau avec les enregistrements:

$persons = Array(
    [0] => Array(
     [id] => 1, 
     [name] => 'Tom', 
     [Photo] => Array(
      [0] => Array(
       [id] => 3, 
       [person_id] => 1, 
       [path] => '~tom/my_dog.jpg', 
       [title] => 'a woof'    // 1st 
      ) 
     ) 
    ), 
    [1] => Array(
     [id] => 2, 
     [name] => 'Fred', 
     [Photo] => Array(
      [0] => Array(
       [id] => 2, 
       [person_id] => 2, 
       [path] => '~fred/my_wife.png', 
       [title] => "I'm Susan"   // 2nd 
      ), 
      [0] => Array(
       [id] => 1, 
       [person_id] => 2, 
       [path] => '~fred/me.png', 
       [title] => "Yo, it's Me!"  // 3rd 
      ) 
     ) 
    ), 
    [2] => Array(
     [id] => 3, 
     [name] => 'Jack', 
     [Photo] => Array() 
    ) 
) 

Un grand merci!

Répondre

4
Select * 
From persons 
left outer join photos on person.id=photos.person_id 
order by photos.title 
+0

+1 me battre, effacé mon propre message :) –

Questions connexes