【问题标题】:Dynamic column alias based on column value基于列值的动态列别名
【发布时间】:2013-05-01 16:10:25
【问题描述】:

我想根据mysql中的列值来命名列别名。这可能吗?

类似的东西;

select  
  case when answer_type = 'RB' then 
     answer_type as 'radio'
 else 
     answer_type as 'evrything_else'
 end case
from  XTable 

【问题讨论】:

  • 如果你想拥有动态别名,你需要创建动态查询。

标签: mysql dynamic alias


【解决方案1】:

不,这在纯 SQL 中是不可能的。您可能必须查询出数据,然后在执行查询的任何应用程序中对其进行处理。

【讨论】:

    【解决方案2】:
    select if(answer_type="RB",true,NULL) as radio, 
    if(answer_type != ="RB",true,NULL) as everything_else
    from XTable;
    

    当您获得一个结果表时,您必须拆分它们,其中来自选择的名称或别名是列标签。此方法可让您检查返回的 radio 的值(以及everything_else 的值)。

    你正在尝试做什么,看看没有办法让列标题工作:

    id | radio MAGICAL OR everytning_else |
    1  | RB                               |
    2  | NOT_RB                           |
    

    我的方法能为你做什么:

    id | radio | everything_else |
    1  | true  | NULL            |
    2  | NULL  | true            |
    

    【讨论】:

    • 是的,我知道这个解决方案。但我想知道一种在单列中执行此操作的方法
    【解决方案3】:

    从 XTable 中选择 if(answer_type="RB",'radio',if(answer_type != "RB",'everything_else',NULL)) 作为 answer_type;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-19
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 2018-06-18
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多