MySQL : how to split text and number with "-" - mysql

I would like to rewrite a number of user id which is splited by "-" between text and number. For example:
KT-12345
BA-98765
CC-98765
ITA-87987
From a huge amount of data which is mixed up with text and number. For example:
KT98798
CC94788
BB87600
So the question is : I would like to make the user id from the 2nd examples into the first one. How to achieve it in MySQL. Please suggest.

SELECT
CASE
WHEN floor(substr(name, 3,1)) > 0
THEN CONCAT_WS('-', SUBSTRING(name, 1, 2), SUBSTRING(name, 3, LENGTH(name)))
ELSE CONCAT_WS('-', SUBSTRING(name, 1, 3), SUBSTRING(name, 4, LENGTH(name)))
END AS new_name
FROM test

No "SELECT" data but UPDATE:
UPDATE `table` SET field = REPLACE(field, '-', '');

here an example how to use it in php
$str = 'abc123';
preg_match('#([a-z]*)(\d*)#', $str, $match);
echo 'alpha: ' . $match[1];
echo 'num: ' . $match[2];?>

Related

Find the substring between the first 'a' char in email column before '#'

I am trying to find the substring between the first 'a' char in email column before '#',
i have written the below sql-query ,
but i think i can do it in better way .
SELECT
email,
CASE
WHEN
LENGTH(SUBSTR(email, 0, POSITION('#' IN email))) - LENGTH(REPLACE(SUBSTR(email, 0, POSITION('#' IN email)),
'a',
'')) > 1
THEN
SUBSTR(email,
POSITION('a' IN email) + 1,
POSITION('a' IN SUBSTR(email,
POSITION('a' IN email) + 1)) - 1)
ELSE ''
END AS deelstring
FROM
persoon
correction for the sql-query
There're at least two ways to extract a substring:
Extract the substring from start position to end position, or
Remove prefix/suffix before/after start/end position
Piggyback on data prepared by #nbk with the 2nd approach, this may work for you:
select email,
regexp_replace(email,'^.*a','') as remove_prefix,
regexp_replace(email,'#.*$','') as remove_suffix,
regexp_replace(regexp_replace(email,'^.*a',''),'#.*$','') as remove_both
from persoon;
Outcome:
email |remove_prefix |remove_suffix|remove_both|
----------------------+-----------------+-------------+-----------+
testa11111111#test.com|11111111#test.com|testa11111111|11111111 |
You have to test every step of your query epecially, when you want to extract parts.
As ysth Length only can count ascii charakter, which doesn't matter when you check for if there are any a in the email, but when extracting you need the length for all characters even non ASCII.
CREATE TABLe persoon (email varchar(50))
INSERT INTO persoon VALUEs('testa11111111#test.com'),('tÚsta11Ú111111#test.com')
Records: 2 Duplicates: 0 Warnings: 0
SELECT
email,
CASE
WHEN
LENGTH(SUBSTR(email, 1, POSITION('#' IN email)-1)) - LENGTH(REPLACE(SUBSTR(email, 1, POSITION('#' IN email)-1),
'a',
'')) >= 1
THEN
SUBSTR(email,
POSITION('a' IN email) + 1,
CHAR_LENGTH (SUBSTR(email, 1, POSITION('#' IN email)-1))
- POSITION('a' IN email) )
ELSE ''
END AS deelstring
FROM
persoon
email
deelstring
testa11111111#test.com
11111111
tÚsta11Ú111111#test.com
11Ú111111
fiddle

MySQL Replace String "John Doe" with "John D"

Have a large name table all as string "Name Surname"
Need to update the entire table, setting the string to be "Name FirstLetterOfSurname" ie. "John Citizen" becomes "John C".
Seems easier to do via PHP eg.
$name = "John Doe";
$expl = explode(' ', $name);
echo $expl [0].' '.$expl[1][0];
John D
wondering about a query to just update the database.
Help Appreciated?
I'd find the location of the space, and take a substring of one character more than that:
SELECT SUBSTR(name, 1, LOCATE(' ', name) + 1)
FROM mytable
Of course, this can also be done as an update instead of just querying the string in the right format:
UPDATE mytable
SET name = SUBSTR(name, 1, LOCATE(' ', name) + 1)
If you want to update the database, please use the following query:
UPDATE TestTable
SET FirstName = CONCAT(LEFT(FirstName, INSTR(FirstName, ' ')) , LEFT(SUBSTRING(FirstName, INSTR(FirstName, ' ') + 1), 1)) ;
Please find the Working Demo with sample data.

Fetch numbers only from an address column in sql

Actually in my case I need to select street number from a address string, which means if the string is '1234 dummy789 road', I only want to get '1234', not '1234789' Another example is 'Plot 111 dummy 1220' then i want only '111'. and if the string is '111/2 dummy' then i want to get '111/2'
I tried following:
SELECT CASE WHEN substr(address , 1, 1) between '0' and '9'
THEN substr(address , 1, 1)
ELSE 'False'
END as add
from test
<?php
$ab = "1225584454 red 1555 blue";
$result = explode(" ", $ab, 2);
print_r($result);
?>
in this case this will gives you first string in your variable.
Assuming that you have civil number followed by space and street name I would suggest the following:
Put WHERE statement with REGEXP to get those, which start with digit-followed-by-space. And in returned field get only numeric portion with substring.
Something like this:
SELECT SUBSTRING(address, 0, LOCATE(' ', address)) FROM items WHERE `address` REGEXP '^[0-9]+ '>0;
Correction:
SELECT TRIM(LEFT(address, LOCATE(' ', address))) FROM items WHERE `address` REGEXP '^[0-9]+ '>0;

Need help formatting CONCAT() for MySQL query

I have a table where I am attempting to take 3 database table values and reformat them in a single value. Here is the SQL statement that I have at the moment:
SELECT
CASE WHEN cb_cardtype = 'Discover Credit Card'
THEN 'DS'
END +
';' + RIGHT(cardnumbers,4) + ';' + LPAD(MONTH(planexpdate), 2, '0') +
'/' + LPAD(YEAR(planexpdate), 2, '0') AS account_billing_key
FROM my_table
So what I wanted to get as an output here would be:
DS;4242;07/14
The problem is that I am using the + to attempt this, which actually adds the values together. Rather, I understand that I need to use CONCAT() to merge the values. I am unclear about how I can pull the individual values and then concatenate them as desired.
If your query is otherwise correct, all you need to do is to wrap all the strings you want to concatenate - comma separated - inside a call to CONCAT;
SELECT
CONCAT(
CASE WHEN cb_cardtype = 'Discover Credit Card' THEN 'DS' END,
';',
RIGHT(cardnumbers,4),
';',
LPAD(MONTH(planexpdate), 2, '0'),
'/',
LPAD(YEAR(planexpdate), 2, '0')
) AS account_billing_key
FROM my_table

Search for text between delimiters in MySQL

I am trying to extract a certain part of a column that is between delimiters.
e.g. find foo in the following
test 'esf :foo: bar
So in the above I'd want to return foo, but all the regexp functions only return true|false,
is there a way to do this in MySQL
Here ya go, bud:
SELECT
SUBSTR(column,
LOCATE(':',column)+1,
(CHAR_LENGTH(column) - LOCATE(':',REVERSE(column)) - LOCATE(':',column)))
FROM table
Yea, no clue why you're doing this, but this will do the trick.
By performing a LOCATE, we can find the first ':'. To find the last ':', there's no reverse LOCATE, so we have to do it manually by performing a LOCATE(':', REVERSE(column)).
With the index of the first ':', the number of chars from the last ':' to the end of the string, and the CHAR_LENGTH (don't use LENGTH() for this), we can use a little math to discover the length of the string between the two instances of ':'.
This way we can peform a SUBSTR and dynamically pluck out the characters between the two ':'.
Again, it's gross, but to each his own.
This should work if the two delimiters only appear twice in your column. I am doing something similar...
substring_index(substring_index(column,':',-2),':',1)
A combination of LOCATE and MID would probably do the trick.
If the value "test 'esf :foo: bar" was in the field fooField:
MID( fooField, LOCATE('foo', fooField), 3);
I don't know if you have this kind of authority, but if you have to do queries like this it might be time to renormalize your tables, and have these values in a lookup table.
With only one set of delimeters, the following should work:
SUBSTR(
SUBSTR(fooField,LOCATE(':',fooField)+1),
1,
LOCATE(':',SUBSTR(fooField,LOCATE(':',fooField)+1))-1
)
mid(col,
locate('?m=',col) + char_length('?m='),
locate('&o=',col) - locate('?m=',col) - char_length('?m=')
)
A bit compact form by replacing char_length(.) with the number 3
mid(col, locate('?m=',col) + 3, locate('&o=',col) - locate('?m=',col) - 3)
the patterns I have used are '?m=' and '&o'.
select mid(col from locate(':',col) + 1 for
locate(':',col,locate(':',col)+1)-locate(':',col) - 1 )
from table where col rlike ':.*:';
If you know the position you want to extract from as opposed to what the data itself is:
$colNumber = 2; //2nd position
$sql = "REPLACE(SUBSTRING(SUBSTRING_INDEX(fooField, ':', $colNumber),
LENGTH(SUBSTRING_INDEX(fooField,
':',
$colNumber - 1)) + 1)";
This is what I am extracting from (mainly colon ':' as delimiter but some exceptions), as column theline255 in table loaddata255:
23856.409:0023:trace:message:SPY_EnterMessage (0x2003a) L"{#32769}" [0081] WM_NCCREATE sent from self wp=00000000 lp=0023f0b0
This is the MySql code (It quickly did what I want, and is straight forward):
select
time('2000-01-01 00:00:00' + interval substring_index(theline255, '.', 1) second) as hhmmss
, substring_index(substring_index(theline255, ':', 1), '.', -1) as logMilli
, substring_index(substring_index(theline255, ':', 2), ':', -1) as logTid
, substring_index(substring_index(theline255, ':', 3), ':', -1) as logType
, substring_index(substring_index(theline255, ':', 4), ':', -1) as logArea
, substring_index(substring_index(theline255, ' ', 1), ':', -1) as logFunction
, substring(theline255, length(substring_index(theline255, ' ', 1)) + 2) as logText
from loaddata255
and this is the result:
# LogTime, LogTimeMilli, LogTid, LogType, LogArea, LogFunction, LogText
'06:37:36', '409', '0023', 'trace', 'message', 'SPY_EnterMessage', '(0x2003a) L\"{#32769}\" [0081] WM_NCCREATE sent from self wp=00000000 lp=0023f0b0'
This one looks elegant to me. Strip all after n-th separator, rotate string, strip everything after 1. separator, rotate back.
select
reverse(
substring_index(
reverse(substring_index(str,separator,substrindex)),
separator,
1)
);
For example:
select
reverse(
substring_index(
reverse(substring_index('www.mysql.com','.',2)),
'.',
1
)
);
you can use the substring / locate function in 1 command
here is a mice tutorial:
http://infofreund.de/mysql-select-substring-2-different-delimiters/
The command as describes their should look for u:
**SELECT substr(text,Locate(' :', text )+2,Locate(': ', text )-(Locate(' :', text )+2)) FROM testtable**
where text is the textfield which contains "test 'esf :foo: bar"
So foo can be fooooo or fo - the length doesnt matter :).