SQL select join: is it possible to prefix all columns as 'prefix.*'?

后端 未结 22 1834
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 06:20

I\'m wondering if this is possible in SQL. Say you have two tables A and B, and you do a select on table A and join on table B:

SELECT a.*, b.* FROM TABLE_A a         


        
22条回答
  •  盖世英雄少女心
    2020-12-02 06:38

    I totally understand your problem about duplicated field names.

    I needed that too until I coded my own function to solve it. If you are using PHP you can use it, or code yours in the language you are using for if you have this following facilities.

    The trick here is that mysql_field_table() returns the table name and mysql_field_name() the field for each row in the result if it's got with mysql_num_fields() so you can mix them in a new array.

    This prefixes all columns ;)

    Regards,

    function mysql_rows_with_columns($query) {
        $result = mysql_query($query);
        if (!$result) return false; // mysql_error() could be used outside
        $fields = mysql_num_fields($result);
        $rows = array();
        while ($row = mysql_fetch_row($result)) { 
            $newRow = array();
            for ($i=0; $i<$fields; $i++) {
                $table = mysql_field_table($result, $i);
                $name = mysql_field_name($result, $i);
                $newRow[$table . "." . $name] = $row[$i];
            }
            $rows[] = $newRow;
        }
        mysql_free_result($result);
        return $rows;
    }
    

提交回复
热议问题