【问题标题】:How to add a new column in relation to existing column in MySql?如何在 MySql 中添加与现有列相关的新列?
【发布时间】:2019-03-24 20:32:33
【问题描述】:

我的 MySql 数据库中已经有一个名为“table1”的现有表,例如,它有一个名为“主题”的列,其中包含如下值:

现在我想在“table1”中添加一个名为“code”的新列,其中包含值:

对于“主题”中的“AAAA”是“S01”,

对于“主题”中的“BBBB”是“S02”,

对于“主题”中的“CCCC”是“S03”,

对于“主题”中的“DDDD”是“S04”。

如图所示:

SQL 查询将如何处理?

【问题讨论】:

    标签: python mysql sql


    【解决方案1】:

    你可以使用一个案例,例如选择

    select  subject 
        , case  
            when subject  ='AAAA' then 'S01'
            when subject  ='BBBB' then 'S02'
            when subject  ='CCCC' then 'S03'
            when subject  ='DDDD' then 'S04'  
        end  code 
    from my_table   
    

    如果你需要更新表格的内容

    update my_table  
    set code = case  
            when subject  ='AAAA' then 'S01'
            when subject  ='BBBB' then 'S02'
            when subject  ='CCCC' then 'S03'
            when subject  ='DDDD' then 'S04'  
        end     
    

    您可以使用

    将列添加到表架构中
    ALTER TABLE my_table    ADD  code  varchar(4) ; 
    

    对于以 'AAAA' 开头的字符串,您可以使用 like 运算符

     when subject  like 'AAAA%' then 'S01'
    

    【讨论】:

      猜你喜欢
      • 2021-08-29
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多