Dynamically assign alias to all the field names in msyql query

前端 未结 1 1365
余生分开走
余生分开走 2021-01-28 19:45

I have 2 tables in mysll DB. Both tables have few fixed and few dynamic columns (Fields / Schema). I want to join both these tables with following query:

SELECT          


        
相关标签:
1条回答
  • 2021-01-28 20:11

    You would need to query the information_schema to get the column names of that two tables. Lets assume You would have the cd column names stored in the array $cd_columns and the cd_n column names in the array $cdn_columns.

    Then in PHP when creating the query loop through the column arrays and do something like this:

    $sql = 'SELECT ';
    
    // add the cd columns
    $i = 0;
    foreach($cd_columns as $col) {
        $sql .= "{$col} AS CD_Column{$i},";
        $i++;
    }
    
    // add the cd_n columns
    $i = 0;
    foreach($cdn_columns as $col) {
        $sql .= "{$col} AS CN_Column{$i},";
        $i++;
    }
    
    // remove the trailing comma
    $sql = trim($sql, ',');
    // continue the SQL
    $sql .= ' FROM ...';
    

    Was this helpful?

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