I have the following example of rows in a MySQl table
Column A
Row1 Lauguage=English&Country=USA&Gender=Male
Row2 Gender=Female&Language=French&Country=
Row3 Country=Canada&Gender=&Language=English
How can I achieve the following: For example, I need to look for Country
End Result: New Column
Column B
Row1 USA
Row2
Row3 Canada
Any help here would be appreciated! Thanks!
The SUBSTRING() function extracts a substring from a string (starting at any position). Note: The SUBSTR() and MID() functions equals to the SUBSTRING() function.
MySQL POSITION() Function The POSITION() function returns the position of the first occurrence of a substring in a string. If the substring is not found within the original string, this function returns 0. This function performs a case-insensitive search. Note: The LOCATE() function is equal to the POSITION() function.
To fetch the first alphabet from the strings, use LEFT(). This method allows you to return characters from the left of the string.
LOCATE() function MySQL LOCATE() returns the position of the first occurrence of a string within a string. Both of these strings are passed as arguments. An optional argument may be used to specify from which position of the string (i.e. string to be searched) searching will start.
You can pick the text following the 'Country=', and then once you have that substring, pick the text before the first '&'
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(ColumnA, 'Country=', -1), '&', 1) AS ColumnB
FROM `atable`
See http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_substring-index
Here's a test to demonstrate:
mysql> SELECT * FROM atable;
+------+------------------------------------------+
| row | columna |
+------+------------------------------------------+
| Row1 | Lauguage=English&Country=USA&Gender=Male |
| Row2 | Gender=Female&Language=French&Country= |
| Row3 | Country=Canada&Gender=&Language=English |
+------+------------------------------------------+
mysql> SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(ColumnA, 'Country=', -1), '&', 1) AS ColumnB FROM atable;
+---------+
| ColumnB |
+---------+
| USA |
| |
| Canada |
+---------+
Re your followup question:
INSERT INTO atable VALUES ('Row4', 'Gender=&Language=English');
SELECT `row`, IF(LOCATE('Country=', ColumnA)>0,
COALESCE(
NULLIF(SUBSTRING_INDEX(SUBSTRING_INDEX(ColumnA, 'Country=', -1), '&', 1), ''),
'Blank string is not valid!'),
'Missing Country!') AS ColumnB
FROM `atable`
+------+----------------------------+
| row | ColumnB |
+------+----------------------------+
| Row1 | USA |
| Row2 | Blank string is not valid! |
| Row3 | Canada |
| Row4 | Missing Country! |
+------+----------------------------+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With