MYSQL + PHP将两行显示的数据作为单个列

时间:2013-01-05 10:30:11

标签: php mysql

我有一个包含以下格式数据的表

region   gender  age_group  population 

Dallas    M        1          200  
Dallas    F        1          500 
NY        M        1          320 
NY        F        1          310 
Dallas    M        2          300 
Dallas    F        2          600 
NY        M        2          400 
NY        F        2          800 

我正在寻找以下列格式输出数据的最佳查询

region/age_group      1           2
Gender             M     F       M    F
Dallas             200   500    300  600
NY                 320   310    400  800

我的查询只返回顶部列和区域。不确定如何将顶部柱子细分为上面出现的性别

SELECT distinct (region), a.group_one, b.group_two 
FROM city_populations c  
LEFT JOIN city_populations AS a ON a.age_group=1 AND c.age_group=a.age_group  
LEFT JOIN city_populations AS b ON b.age_group=2 AND c.age_group=a.age_group  

1 个答案:

答案 0 :(得分:1)

//首先我从数据库中获取了所有数据

$result = mysql_query("select * from test2")or die(mysql_error());
$regions = array();
$age_groups = array();
while($det = mysql_fetch_array($result)){

    if(!in_array($det['region'], $regions)){
        $regions[] = $det['region'];
    }
    if(!in_array($det['age_group'], $age_groups)){
        $age_groups[] = $det['age_group'];
    }
    $rows[] = $det;
}

//然后在php中处理以显示您想要的

echo "<table>";
echo "<tr><td>Age group</td>";
foreach($age_groups as $keyAG => $valueAG){
    echo "<td colspan='2'>$valueAG</td>";
}
echo "</tr>";
echo "<tr><td>Gender</td>";
foreach($age_groups as $keyAG => $valueAG){
    echo "<td>M</td>";
    echo "<td>F</td>";
}
echo "</tr>";
foreach($regions as $keyR => $valueR){

    echo "<tr>";
    echo "<td>".$valueR."</td>";
    foreach($age_groups as $keyAG => $valueAG){

        foreach($rows as $keyROWS => $valueROWS){
            if($valueROWS['region'] == $valueR && $valueROWS['age_group'] == $valueAG){
                if($valueROWS['gender'] == 'M'){
                    echo "<td>".$valueROWS['population']."</td>";
                }
                elseif($valueROWS['gender'] == 'F'){
                    echo "<td>".$valueROWS['population']."</td>";
                }
            }
        }
        $data[$valueR][$valueAG] = array($maleValue, $femaleValue);

    }
    echo "</tr>";
}
echo "</table>";

注意:强烈建议使用mysqli_ *而不是mysql。