Just to learn SQL I wanted to make a hierarchy with a simple parent - child. Like the stack overflow badges (Parent: Question Badges, Child: Altruist).
This is my sq
It is not possible to achieve this with SQL query, because (due to relational model nature) SQL query will always return "flat" resultset without any nesting (rare exceptions are vendor SQL extensions, targetted on generating XML output or alike, but MySQL has no such extensions).
If you want to get nested arrays from SQL resultset, you have to postprocess it with PHP code. This code may be organized like grouping loop over an array (presorted with SQL), starting new group every time a key of "inner" table changes. This can be done in PHP in rather universal way, so you can write one such funciton to postprocess many SQL queries (giving it appropriate parameters).
ADDITION Here is such a function:
function groupnest( $data, $groupkey, $nestname, $innerkey ) {
$outer0 = array();
$group = array(); $nested = array();
foreach( $data as $row ) {
$outer = array();
while( list($k,$v) = each($row) ) {
if( $k==$innerkey ) break;
$outer[$k] = $v;
}
$inner = array( $innerkey => $v );
while( list($k,$v) = each($row) ) {
if( $k==$innerkey ) break;
$inner[$k] = $v;
}
if( count($outer0) and $outer[$groupkey]!=$outer0[$groupkey] ) {
$outer0[$nestname] = $group;
$nested[] = $outer0;
$group = array();
}
$outer0 = $outer;
$group[] = $inner;
}
$outer[$nestname] = $group;
$nested[] = $outer;
return $nested;
}
data
is array (SQL resultset) to be nested,
groupkey
is column name of the 'outer' entity primary key,
nestname
is name of the field into which 'inner rows' will be put,
innerkey
is column name of the 'inner' entity primary key.
In the resultset all columns of 'outer' entity must preceed $innerkey
column and all columns of 'inner' entity must follow it.
To be grouped correctly, resultset must be firstly ordered by a unique expression from 'outer' entity, like order by badge_type_title, badge_type_id, ...
. Later fields in order by
will define ordering inside 'inner' groups.
To nest join of 3 or more entities you can use this function several times (folding "from inside to outside")