我有员工表,其中包含以下结构和数据。
id name empDetails phone
1 John phone:7845982563,pinCode:7895645,subCode:22
2 pitt phone:7889451524,pinCode:2565479,subCode:24
3 ken empId:3243,phone:283241524,pinCode:2563479,subCode:25
4 rancho empId:3263,phone:454424154,pinCode:5565479,subCode:24
. . .
Sometimes phone poistion will be after empId also.
现在我想检查列empDetails
如果是,请使用字符串电话,然后获取电话号码并将其插入同一行的新电话栏中。
我们可以通过这种方式检查记录是否包含字符串电话。
SELECT employee.empDetails FROM employee WHERE employee.empDetails LIKE '%phone:%'
但我们如何才能将电话号码转换为另一列并将其插入同一记录?
谢谢, 雅利安
答案 0 :(得分:2)
update employee.empDetails set phone = cast(replace(empDetails, 'phone:', '') as unsigned)
where employee.empDetails LIKE '%phone:%'
假设电话号码将始终以'phone:'为前缀
不是一个干净的答案。但是会做到这一点:)
答案 1 :(得分:1)
SELECT replace(SUBSTRING_INDEX(empDetails,',',1),'phone:','') as phone
FROM Table1
where empDetails REGEXP '[[:<:]]phone[[:>:]]';
检查工作小提琴: http://sqlfiddle.com/#!2/802d2/18
请遵循spaceman817的建议,使用单独的列。
希望这会有所帮助。
〜ķ
假设您的手机可以处于任何位置的开始,中间和结束。例如:
(1, 'John', 'phone:7845982563,pinCode:7895645,subCode:22'),
(2, 'pitt', 'pinCode:2565479,subCode:24,phone:7889451524'),
(3, 'vk', 'pinCode:2565479,phone:7889451524,subCode:24');
使用以下查询:
SELECT
replace(SUBSTRING_INDEX(SUBSTRING(empDetails,LOCATE('phone:',empDetails)),',',1),'phone:','') as phone
FROM Table1 where empDetails REGEXP '[[:<:]]phone[[:>:]]';
--- --- OUTPUT
PHONE
7845982563
7889451524
7889451524
检查更新sql fiddle with working example:
希望这会有所帮助!
答案 2 :(得分:0)
尝试
update employee set
phone = SUBSTR(SUBSTRING_INDEX(empDetails,'phone:',-1) from 1 for instr(SUBSTRING_INDEX(empDetails,'phone:',-1),',')-1)
where employee.empDetails LIKE '%phone:%'