简体   繁体   中英

Create a new column based on value of a column in MYSQL table

I have a Mysql table which has a requestID column. requestId is of type String. I have three type of requestID. Let's say bed , tv and fridge .

  • For bed type of request, nothing is appended in requestID. eg abc123
  • For tv and fridge type of request, requestId is appended by tv and fridge respectively. eg abc123.tv or abc123.fridge

I need to create a new table which has all columns plus column requestType which has entry bed , tv or fridge .

Input

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

Output

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

You can use SUBSTRING_INDEX to get the requestType column as the characters after . in the string. Then use CREATE TABLE AS..SELECT.. to create a new table with all the existing columns and the newly computed one.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM