我需要从两个表中获取所有列(包括重复列)。我获取了所有数据,但重复列没有对别名的任何引用。我觉得数据应该像这样回来(但事实并非如此。):
[0] => Array
(
[0] => 1
[Alias1.id] => 1
[1] => bay area
[Alias1.city] => bay area
[2] => CA
[Alias1.state] => CA
[3] => 1
[Alias2.id] => 1
[4] => san francisco
[Alias2.city] => san francisco
[5] => giants
[Alias2.baseball_team] => giants
)
但相反,数据会像这样回来:
[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
)
以下是查询:
$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();
此问题是 How to return mysql data using table aliases with left join and duplicate columns
的精确问题答案 0 :(得分:1)
以这种方式试试
SELECT Alias1.id `Alias1.id`,
Alias1.city `Alias1.city`,
Alias1.state `Alias1.state`,
Alias2.id `Alias2.id`,
Alias2.city `Alias2.city`,
Alias2.baseball_team `Alias2.baseball_team`
FROM table1 AS Alias1 LEFT JOIN table2 AS Alias2
ON Alias1.id = Alias2.id
示例输出:
| ALIAS1.ID | ALIAS1.CITY | ALIAS1.STATE | ALIAS2.ID | ALIAS2.CITY | ALIAS2.BASEBALL_TEAM | |-----------|-------------|--------------|-----------|---------------|----------------------| | 1 | bay area | CA | 1 | san francisco | giants |
这是 SQLFiddle 演示
答案 1 :(得分:0)
它正在做的是正确的,如果您希望将表名作为column_name的一部分,则必须将select语句更改为以下内容:
选择Alias1.id为`Alias1.id`,
Alias1.city为“Alias1.city”,
Alias1.state为“Alias1.state”,
Alias2.id为“Alias2.id”,
Alias2.city为“Alias2.city”,
Alias2.baseball_team为“Alias2.baseball_team”