簡體   English   中英

根據MYSQL表中的列值創建一個新列

[英]Create a new column based on value of a column in MYSQL table

我有一個Mysql表,其中有一個requestID列。 requestId的類型為String。 我有三種類型的requestID。 假設bedtvfridge

  • 對於請求的bed類型,requestID中未附加任何內容。 例如abc123
  • 對於tvfridge類型的請求,分別在tvfridge附加requestId。 例如abc123.tvabc123.fridge

我需要創建一個新表,其中包含所有列以及具有入口bedtvfridgerequestType

輸入項

| 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM