gpt4 book ai didi

mysql - 根据MYSQL表中列的值创建新列

转载 作者:行者123 更新时间:2023-11-29 11:01:19 26 4
gpt4 key购买 nike

我有一个 Mysql 表,其中有一个 requestID 列。 requestId 是 String 类型。我有三种类型的 requestID。假设电视冰箱

  • 对于 bed 类型的请求,requestID 中不会附加任何内容。例如abc123
  • 对于 tvfridge 类型的请求,requestId 分别附加 tvfridge。例如 abc123.tvabc123.fridge

我需要创建一个新表,其中包含所有列以及列 requestType,其中包含条目 bedtvfridge

输入

| ID | RequestId     |
| 1 | abc123 |
| 2 | abc123.tv |
| 3 | abc123.fridge |

输出

| ID | RequestId     |  RequestType |     
| 1 | abc123 | bed |
| 2 | abc123.tv | tv |
| 3 | abc123.fridge | fridge |

最佳答案

您可以使用 SUBSTRING_INDEX 来获取 requestType 列,作为字符串中 . 后面的字符。然后使用 CREATE TABLE AS..SELECT.. 创建一个包含所有现有列和新计算的列的新表。

create table newtable as 
select e.*,
case when substring_index(requestID,'.',-1)=requestID then 'bed'
else substring_index(requestID,'.',-1) end as requestType
from existing_table e

关于mysql - 根据MYSQL表中列的值创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42193411/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com