如何使用左连接和重复列的表别名返回mysql数据

时间:2013-11-21 22:46:37

标签: mysql mysqli

我正在尝试使用表别名执行简单的左连接,以此格式返回两个表中的所有值:

[Alias1] => Array
    (
        [id] => 1
        [city] => bay area
        [state] => CA
    )

[Alias2] => Array
    (
        [id] => 1
        [city] => san francisco
        [baseball_team] => giants

     )

这是我非常简单的mysqli_query:

$result = mysqli_query($sql, SELECT  Alias1.id, Alias1.city, Alias1.state, Alias2.id, Alias2.city, Alias2.baseball_team FROM database.table1 AS Alias1 LEFT JOIN database.table2 AS Alias2 ON Alias1.id = Alias2.id)

要获得结果......我使用:

while($row = mysqli_fetch_array($result))
{
     $data[] = $row;
}
print_r($data);die();

问题:数据打印出来:

 [0] => Array
        (
            [0] => 1
            [id] => 1
            [1] => bay area
            [city] => bay area
            [2] => CA
            [state] => CA
            [3] => 1
            [4] => san francisco
            [5] => giants
            [baseball_team] => giants
        )

其他信息:我最初尝试使用mysql_fetch_assoc($ result)获取数据......但重复的列根本不会返回。

1 个答案:

答案 0 :(得分:0)

而不是:

$data[] = $row;

使用它来形成您想要的数据数组:

$data['Alias1'] = array(
    "id"=>$row['id'],
    "city"=>$row['1_city'],
    "state"=>$row['state'],
);
$data['Alias2'] = array(
    "id"=>$row['id'],
    "city"=>$row['2_city'],
    "baseball_team"=>$row['baseball_team'],
);

或者,如果您期望多行,则需要使用以下内容:

$data[] = array(
    "Alias1" => array(
        "id"=>$row['id'],
        "city"=>$row['1_city'],
        "state"=>$row['state'],
    ),
    "Alias2" => array(
        "id"=>$row['id'],
        "city"=>$row['2_city'],
        "baseball_team"=>$row['baseball_team'],
    ),
);

注意: 如果您的两个表之间的城市值不同,那么您应该使用别名,以便您可以不同地拉另一个。如果它们是相同的,我建议你不要在数据库中列出两次,因为这会复制数据并使数据库非规范化。

修改 您的查询应该是

SELECT  Alias1.id, Alias1.city AS 1_city, Alias1.state, Alias2.id, Alias2.city AS 2_city, Alias2.baseball_team FROM database.table1 AS Alias1 LEFT JOIN database.table2 AS Alias2 ON Alias1.id = Alias2.id

请参阅上面针对这些别名的已编辑答案。