I am looking at a table with phone1, phone2 and mobile. However the phone strings are not formatted properly.
The phone numbers are basically free text like this:
row1: phone1:19123123123
row2: mobile:+1 912 123 123
row3: phone2:1 912 123 123
row4: mobile:(+1) 912 123 123
row5: phone2:(+1)912-123-123
Is it possible to write a SQL query to find if one of the fields phone1, phone2 or mobile is +19123123123 but it needs to be able to match any one of those free text examples? Thanks
So in the above example, it should return all 5 records be those free text match that phone number and is in one of the 3 fields.
Assuming the only numbers and +
in the column are in the phone number, you can use:
where regexp_replace(col, '[^+0-9]', '') = '+19123123123'
This removes everything that is not a +
or digit.
you can use Regex to identify phone number pattern or you can just remove all parenthesis and spaces from the both side of the where clause and then compare.
SELECT * FROM T
WHERE REPLACE(REPLACE(REPLACE(phone1, '(',''),')',''),' ','') = '+19123123123'
OR REPLACE(REPLACE(REPLACE(phone1, '(',''),')',''),' ','') = '19123123123'
OR REPLACE(REPLACE(REPLACE(phone2, '(',''),')',''),' ','') = '+19123123123'
OR REPLACE(REPLACE(REPLACE(phone2, '(',''),')',''),' ','') = '19123123123'
OR REPLACE(REPLACE(REPLACE(mobile, '(',''),')',''),' ','') = '+19123123123'
OR REPLACE(REPLACE(REPLACE(mobile, '(',''),')',''),' ','') = '19123123123'
As suggested by Juergen, you can strip all non numeric character and compare. If you are on MySQL 8.0+, you can use below code
REGEXP_REPLACE(SUBSTRING_INDEX(column_name, ':', -1),'[^0-9]+',"")
Assumption: Column value is always being separated by colon(:) after mobile/phone/sometext. Here it will take the second part of your string after colon and then strip the non numeric characters
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.