PHP MySQL mysql_fetch_assoc with array keys distinguished by 'as' designations

前端 未结 1 1977
终归单人心
终归单人心 2020-12-21 11:13

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_

相关标签:
1条回答
  • 2020-12-21 11:35

    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];
    

    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.

    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.

    0 讨论(0)
提交回复
热议问题