Mysql - 1:n关系

时间:2012-07-31 12:38:56

标签: php mysql

A table : id, name
B table : id, a_id, name

1A:nB

我想选择A中的记录和B中的相关信息,结果如下

array( 
    0 => aID_1, 
    aName_1, 
    array (
       bName_1, 
       bName2 , .v.v.v
    ),
  ... 
  ...
)

我可以仅在查询时使用吗?

2 个答案:

答案 0 :(得分:1)

$qry = mysql_query ("SELECT a.id, a.name, b.name as b_name FROM A LEFT JOIN B on A.id = B.a_id");
$data = array ();
while ($r = mysql_fetch_rows($qry))
{
    if (!array_key_exists($r["id"], $data)
    {
        $data[$r["id"]] = array (
            "id" => $r["id"],
            "name" => $r["name"],
            "b" => array ()
        );
    }

    $data[$r["id"]]["b"][] = $r["b_name"];
}

现在你可以通过foreach迭代:

foreach ($data as $d)
{
    print_r($d);
}

答案 1 :(得分:1)

类似的东西:

SELECT * FROM tableA as a LEFT JOIN tableB as b ON a.id = b.a_id;