【问题标题】:Dynamically assign alias to all the field names in msyql query为mysql查询中的所有字段名动态分配别名
【发布时间】:2012-06-06 14:17:22
【问题描述】:

我在 mysll 数据库中有 2 个表。这两个表都有很少的固定列和很少的动态列(字段/模式)。我想通过以下查询加入这两个表:

SELECT *
FROM `cd` cd
LEFT JOIN cd_n cn ON cd.id = cn.fk_cd

我想要结果为

CD_Column1   CD_Column1   CD_Column3   ...... CN_Column1   CN_Column2   CN_Column3  .....
value        value        value        ...... value        value        value       ...       
value        value        value        ...... value        value        value       ...       

其中.....是两个表的动态列名。 所以情况是我不知道列名,因为它们是动态的,我想在查询级别重命名(别名)它。请告诉我该怎么做?

【问题讨论】:

  • 为什么需要在数据库端做呢?您可以在应用程序端检查结果列来自哪个表。

标签: php mysql dynamic schema alias


【解决方案1】:

您需要查询information_schema 以获取这两个表的列名。假设您将cd 列名存储在数组$cd_columns 中,cd_n 列名存储在数组$cdn_columns 中。

然后在 PHP 中通过列数组创建查询循环并执行以下操作:

$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 ...';

这有帮助吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 2020-10-15
    相关资源
    最近更新 更多