1
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
    ),
  ... 
  ...
)

我可以只做查询吗?

4

2 回答 2

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);
}
于 2012-07-31T12:44:07.970 回答
1

像这样的东西:

SELECT * FROM tableA as a LEFT JOIN tableB as b ON a.id = b.a_id;
于 2012-07-31T12:45:02.453 回答