[英]Create a new column based on value of a column in MYSQL table
我有一個Mysql表,其中有一個requestID列。 requestId的類型為String。 我有三種類型的requestID。 假設bed
, tv
和fridge
。
bed
類型,requestID中未附加任何內容。 例如abc123
tv
和fridge
類型的請求,分別在tv
和fridge
附加requestId。 例如abc123.tv
或abc123.fridge
我需要創建一個新表,其中包含所有列以及具有入口bed
, tv
或fridge
列requestType
。
輸入項
| 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.