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

后端 未结 22 1826
爱一瞬间的悲伤
爱一瞬间的悲伤 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:40

    PHP 7.2 + MySQL/Mariadb

    MySQL will send you multiple fields with the same name. Even in the terminal client. But if you want an associative array, you'll have to make the keys yourself.

    Thanks to @axelbrz for the original. I've ported it to newer php and cleaned it up a little:

    function mysqli_rows_with_columns($link, $query) {
        $result = mysqli_query($link, $query);
        if (!$result) {
            return mysqli_error($link);
        }
        $field_count = mysqli_num_fields($result);
        $fields = array();
        for ($i = 0; $i < $field_count; $i++) {
            $field = mysqli_fetch_field_direct($result, $i);
            $fields[] = $field->table . '.' . $field->name; # changed by AS
            #$fields[] = $field->orgtable . '.' . $field->orgname; # actual table/field names
        }
        $rows = array();
        while ($row = mysqli_fetch_row($result)) {
            $new_row = array();
            for ($i = 0; $i < $field_count; $i++) {
                $new_row[$fields[$i]] = $row[$i];
            }
            $rows[] = $new_row;
        }
        mysqli_free_result($result);
        return $rows;
    }
    
    $link = mysqli_connect('localhost', 'fixme', 'fixme', 'fixme');
    print_r(mysqli_rows_with_columns($link, 'select foo.*, bar.* from foo, bar'));
    

提交回复
热议问题