简体   繁体   English

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

[英]Sorting records in a 1:n (one-to-many) relationship

I've got 2 tables: 我有2张桌子:

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

which has are in this relationship: 具有这种关系:

Person hasMany Photo <-> Photo belongsTo Person 人物hasMany很多照片<->照片属于人物

I'd like to list all the persons with their photos (even if someone does not have one, like Jack) and order by photos' title. 我想列出所有带照片的人(即使没有人像杰克一样),并按照片标题排序。

What SQL query (MySQL) should I write for this? 我应该为此编写什么SQL查询(MySQL)? Can I use joins in a one-to-many relationship? 我可以在一对多关系中使用联接吗?

PS: Just as an information, I'd like to be able to construct a such array with the records: 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()
    )
)

Many thanks! 非常感谢!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM