SQL Select * from multiple tables

前端 未结 5 1735
[愿得一人]
[愿得一人] 2020-12-05 15:35

Using PHP/PDO/MySQL is it possible to use a wildcard for the columns when a select is done on multiple tables and the returned array keys are fully qualified to avoid column

5条回答
  •  天涯浪人
    2020-12-05 16:03

    Shamelessly repackaged from @goat:

    // Workaround for setAttribute(PDO::ATTR_FETCH_TABLE_NAMES, true);
    function pdoStatementExecuteAndFetchObjWithTableNames(PDOStatement $statement)
    {
      $statement->setFetchMode(PDO::FETCH_NUM);
      $statement->execute();
    
      //build our associative array keys
      $qualifiedColumnNames = array();
      for ($i = 0; $i < $statement->columnCount(); $i++) {
          $columnMeta = $statement->getColumnMeta($i);
          $qualifiedColumnNames[] = "$columnMeta[table].$columnMeta[name]";
      }
    
      //fetch results and combine with keys
      while ($row = $statement->fetch()) {
          $qualifiedRow = array_combine($qualifiedColumnNames, $row);
          yield (object) $qualifiedRow;
      }  
    }
    

    NOTE: if you use:

    SELECT 1 FROM my_table AS my_table_alias

    then you will get my_table. I would have hoped for my_table_alias. I got this result with PHP 5.6 and sqlite driver.

提交回复
热议问题