PHP MySQL mysql_fetch_assoc,数组键以"as"名称区分 [英] PHP MySQL mysql_fetch_assoc with array keys distinguished by 'as' designations
问题描述
说我做一个像select * from table as t1 LEFT JOIN table as t2 ON t1.id=t2.rank
的自联接,然后获取结果以使用mysql_fetch_assoc
在php中建立一个数组...然后print_r
该数组...有没有办法(不仅是数字,而是使用关联标识符)来区分联接中选择的列和原始列?
Say I do a self-join like select * from table as t1 LEFT JOIN table as t2 ON t1.id=t2.rank
, then fetch results to build an array in php using mysql_fetch_assoc
... then print_r
the array... Is there a way (not just numbers, but using associative identifiers) to distinguish the columns selected in the join, vs the original?
推荐答案
只要使用*
通配符,就会发现具有相同名称的列将覆盖关联数组中的相同键.
As long as you are using the *
wildcard, you will find columns of the same name will overwrite the same keys in your associative array.
您必须为至少一个表中的列赋予列别名:
You must give column aliases to columns from at least one of the tables:
select t1.*, t2.col1 as t2col1, t2.col2 as t2col2, ...
from table as t1 LEFT JOIN table as t2 ON t1.id=t2.rank
否则,您可以使用通配符,但以行数组的形式获取该行:
Or else you can use the wildcard, but fetch the row as an ordinal array:
$row = mysql_fetch_array($result, MYSQL_NUM);
echo $row[4];
您的评论:SQL仅具有*
通配符,其含义是给定表中的所有列,以其自然名称表示".您必须在逐列的基础上显式地对列进行别名.
Re your comment: SQL has just the *
wildcard meaning "all columns from a given table, by their natural names." You must alias columns explicitly, on a column-by-column basis.
例外:如果您使用SQLite,则有一个 pragma full_column_names
选项结果集返回合格的列名,因此您可以使用*
,但是键以表别名为前缀.这是特定于SQLite的非标准SQL.
Exception: If you use SQLite, there's a pragma full_column_names
option that makes the result set return qualified column names, so you can use *
but the keys come back prefixed with the table aliases. This is SQLite-specific and nonstandard SQL.
这篇关于PHP MySQL mysql_fetch_assoc,数组键以"as"名称区分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!