我有一个包含以下字段的表:
row_id
first_field
second_field
row_id 是整数类型,设置为自增,是主键。其他两个字段是文本类型。
表格最多填充五行。因此,row_id 的值为 1、2、3、4 和 5。
我还有另一个结构相似的表,它与我的第一个表有一对多的对应关系。
当我执行选择查询并将结果提供给 mysql_fetch_array 时,发生了一些奇怪的事情。
当我运行这个时:
$query = "select a.*, b.* from table1 as a
left join table2 as b on a.row_id = b.row_id";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<pre>'; print_r($row); echo '</pre>';
}
我明白了:
Array
(
[0] => 1
[row_id] => 1
[1] => some text
[first_field] => some text
[2] => some text
[second_field] => some text
}
Array
(
[0] => 2
[row_id] => 2
[1] => some text
[first_field] => some text
[2] => some text
[second_field] => some text
}
Array
(
[0] => 3
[row_id] =>
[1] => some text
[first_field] => some text
[2] => some text
[second_field] => some text
}
Array
(
[0] => 4
[row_id] =>
[1] => some text
[first_field] => some text
[2] => some text
[second_field] => some text
}
Array
(
[0] => 5
[row_id] =>
[1] => some text
[first_field] => some text
[2] => some text
[second_field] => some text
}
在每个数组结果中,我想将您的注意力引向第一个字段 row_id。在前两个数组中,索引 0 和 row_id 具有相同的值,而在随后的三个数组中,只有索引 0 具有值。 row_id 似乎为空。
这是我第一次遇到这样的事情。是什么原因造成的?这怎么能解决?
谢谢!
最佳答案
这与您在查询中LEFT JOIN
ed 另一个表这一事实有关。
使用 LEFT JOIN
,第一个表中没有匹配行的行在第二个表中的 JOIN
ed 字段中填充了 NULL
值。
因为您在两个表中都有一个名为 row_id
的列,并且您从两个表中都选择了 *
,所以 row_id
的后面的值将被覆盖结果越早。 table2
中似乎没有与 table1
中的第 3、4 和 5 行匹配的行。这导致 NULL row_id
。
解决方案是选择您想要的 row_id
,有多种方法可以做到这一点。但是对于像这样的一组相对简单的结果,我建议您明确说明您想要的所有列:
SELECT a.*, b.col_1, b.col_2
FROM table1 a
LEFT JOIN table2 b ON a.row_id = b.row_id
或者,您可以从连接中删除 LEFT
,结果中将省略第 3、4 和 5 行。
关于php - mysql_fetch_array 返回一个数组,其值为数字索引,但对应的关联索引为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10031292/