以1:n(一对多)关系对记录进行排序

时间:2009-08-09 19:38:25

标签: sql mysql orm entity-relationship one-to-many

我有两张桌子:

+-----------+  +------------------------------------+--------------+
+ 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       |
+-----------+  +---------------------------------------------------+

在这种关系中:

  

人有很多照片< - >照片所属的人

我想列出所有人的照片(即使有人没有像杰克一样)并按照照片的标题排序。

我应该为此编写什么SQL查询(MySQL)?我可以在一对多关系中使用连接吗?

PS:作为一个信息,我希望能够用记录构建一个这样的数组:

$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()
    )
)

非常感谢!

1 个答案:

答案 0 :(得分:4)

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