只是为了学习 SQL,我想用一个简单的父子创建一个层次结构。就像堆栈溢出徽章(父母:问题徽章,孩子:利他主义者)。
这是我的 sql:
SELECT *
FROM (`badge_types`)
LEFT JOIN `badges` ON `badges`.`badge_type` = `badge_types`.`badge_type_id`
这就是我得到的:
(
[0] => stdClass Object
(
[badge_type_id] => 2
[badge_type_title] => Participation Badges
[badge_type_description] => Badges earning by participating in various areas of the site.
[badge_type_order] => 2
[badge_id] => 1
[badge_name] => Autobiographer
[badge_level] => 3
[badge_requirement] => Completed all user profile fields
[badge_type] => 2
[badge_order] => 1
[badge_sites] => 0
)
[1] => stdClass Object
(
[badge_type_id] => 1
[badge_type_title] => Experience Badges
[badge_type_description] => Badges earned by amount of experience gain throughout the site.
[badge_type_order] => 1
[badge_id] => 2
[badge_name] => Apprentice
[badge_level] => 3
[badge_requirement] => Achieved 500 experience
[badge_type] => 1
[badge_order] => 1
[badge_sites] => 0
)
)
我怎样才能把它变成:
array(
array(
[badge_type_id] => 2
[badge_type_title] => Participation Badges
[badge_type_description] => Badges earning by participating in various areas of the site.
[badge_type_order] => 2
[badges] => array(
array(
[badge_id] => 1
[badge_name] => Autobiographer
[badge_level] => 3
[badge_requirement] => Completed all user profile fields
[badge_type] => 2
[badge_order] => 1
[badge_sites] => 0
),
array(
[badge_id] => 2
[badge_name] => Example 2
[badge_level] => 3
[badge_requirement] => blah bla
[badge_type] => 2
[badge_order] => 1
[badge_sites] => 0
)
)
),
array(
[badge_type_id] => 1
[badge_type_title] => Experience Badges
[badge_type_description] => Badges earned by amount of experience gain throughout the site.
[badge_type_order] => 1
[badges] => array(
array(
[badge_id] => 2
[badge_name] => Apprentice
[badge_level] => 3
[badge_requirement] => Achieved 500 experience
[badge_type] => 1
[badge_order] => 1
[badge_sites] => 0
),
array(
[badge_id] => 2
[badge_name] => Example 2
[badge_level] => 3
[badge_requirement] => Achieved 1000 experience
[badge_type] => 1
[badge_order] => 1
[badge_sites] => 0
)
)
)
)
我可以使用多个 MySQL 查询来做到这一点,但理想情况下,如果可能的话,我只想使用一个查询?