Mysql - Calculate soundex difference between two strings - mysql

I have some song names and their pre-calculated soundex stored in a mysql table. I want to compare the soundex of user input with the pre-calculated soundex'es. And get the results in ascending order of difference between the user input and song name.
I have tried the following query (in java):
String query="SELECT * FROM song ORDER BY STRCMP(pre_calculated_soundex,SOUNDEX("+user_input+")) ASC ";
But strcmp only returns 1,0 or -1. So ordering is not correct.
Also tried WHERE pre_calculated_soundex=SOUNDEX(user_input), but this just returns exactly matching soundex.

Completely low-tech and assuming that only first four characters of soundex function is being used and also assuming that "aaaa" is the user input
SELECT *
FROM song
ORDER BY Substr(pre_calculated_soundex, 1, 1) =
Substr(Soundex("aaaa"), 1, 1)
+ Substr(pre_calculated_soundex
, 2, 1) =
Substr
(Soundex("aaaa"), 2, 1)
+ Substr(pre_calculated_soundex, 3, 1)
= Substr(Soundex("aaaa"), 3, 1)
+ Substr(pre_calculated_soundex, 4, 1
)
= Substr(Soundex("aaaa"), 4, 1)

Related

Add hyphen in a string after every 2 characters using in mysql select statement

I have a mysql table with some data. In that i have a column(mobile_number) and that column value is like mobile number (ex:1234587920).
my expected out put is : 12-34-58-79-20
I want to add hyphen after every two numbers.
use concat() for joining strings and use substr() for split a string in mysql :
split (column,start,count) select column from start position for count charachter
concat(column1,"-",column2) will be column1-column2
SELECT CONCAT(SUBSTR(phone,1,2),'-',SUBSTR(phone,3,2),'-',SUBSTR(phone,5,2),'-
',SUBSTR(phone,7,2),'-',SUBSTR(phone,9,2)) FROM `table`
I would definitely use concat_ws() for this:
select concat_ws('-',
substr(mobile_number, 1, 2),
substr(mobile_number, 3, 2),
substr(mobile_number, 5, 2),
substr(mobile_number, 7, 2)
)
Here is a db<>fiddle.
this will work:
SELECT concat(SUBSTRING("1234587920", 1, 2),"-",SUBSTRING("1234587920",3,2),"-
",SUBSTRING("1234587920", 5, 2),"-",
SUBSTRING("1234587920", 7, 2),"-",
SUBSTRING("1234587920", 9, 2)) AS ExtractString;
for your table query is like :
SELECT concat(SUBSTRING(mobile_number, 1, 2),"-
",SUBSTRING(mobile_number,3,2),"-",SUBSTRING(mobile_number, 5, 2),"-",
SUBSTRING(mobile_number, 7, 2),"-",
SUBSTRING(mobile_number, 9, 2)) ExtractString from tablename;
you can use substr and contact_ws command in mysql
update tmp_pay SET date_fix = concat_ws('-',substr(date_at,1,4),substr(date_at,5,6),'01') ;
you can try this
select concat( right(phone_number,3) , "-" , mid(phone_number,4,3) , "-", right(phone_number,4)) from table

SQL how to add a leading 0

Any help would be greatly appreciated.. Im quite new to mySQL and figured there has to be an easier way to update my database.
So my issue is that I have a number of records that don't have a leading zero but I need the total number of characters in any record to be 5.
e.g. 6930 should in fact be 06930
I came across this code but I am unable to get it to work correctly, could anyone point me in the right direction.
UPDATE `it_asset_register`.`tab_id_master`
SET tab_id_master.ID = LEFT('00000', 5-LEN(tab_id_master.ID)) + tab_id_master.ID
WHERE ID = '8407' AND LEN(tab_id_master.ID)<5 AND Len(tab_id_master.ID)>0;
Thanks
LPAD should do the job here:
SELECT LPAD ('123', 5, '0');
00123
SELECT LPAD ('12345', 5, '0');
12345
Try:
UPDATE `it_asset_register`.`tab_id_master`
SET tab_id_master.ID = LPAD (tab_id_master.ID, 5, '0')
WHERE ID = '8407' AND LENGTH(tab_id_master.ID)<5 AND LENGTH(tab_id_master.ID)>0;
To concatenate two or more strings in MySQL, you must use the CONCAT() function.
A possible solution can be:
UPDATE tab_id_master
SET id = SUBSTRING(CONCAT('00000', id), -5)
WHERE LENGTH(id) > 0 AND LENGTH(id) < 5;
Alternatively you can use the LPAD() function:
UPDATE tab_id_master
SET id = LPAD(id, 5, '0')
WHERE LENGTH(id) > 0 AND LENGTH(id) < 5;
Regards
UPDATE
table_name
SET
column_name = RIGHT('00000' + CAST(column_name AS CHAR), 5)
This concatenates the 5 zeros and your ID to something like '000001234'. Then it selects the 5 rightmost characters.
You didn't specify tab_id_master.ID type. If it is of a numeric type you wouldn't be able to store a number with leading zeros but otherwise you could use LPAD():
SET tab_id_master.ID = LPAD(tab_id_master.ID, 5, 0)

mysql + all numbers from one field to Sum

Is it possible to sum the digits in a string and sort by that?
Example values: 19, 21
19 Should be transformed to 10. Explanation: 1+9=10
21 Should be transformed to 3. Explanation: 2+1= 3
After calculating these results, the table needs to be sorted by the resulting values (using SORT BY).
Originally, I have those values stored as JSON array, so it's ["1","9"] and ["2","1"], and in order to parse the JSON I'm using replace as follows:
REPLACE(REPLACE(REPLACE(item_qty, '["', ''), '"]', ''), '","', '')
How about trying something like:
SELECT (
SUBSTRING('["1","9"]', 3, 3) +
SUBSTRING('["1","9"]', 7, 7)
) AS sumOfDigits;
And then if the value ["1","9"] is stored in a column named json and the table is named table you van do:
SELECT * FROM (
SELECT table.*, (
SUBSTRING('json', 3, 3) +
SUBSTRING('json', 7, 7)
) AS sumOfDigits
FROM table
) tmp
ORDER BY sumOfDigits;
I would define a function to do the sum, as follow:
DELIMITER //
CREATE FUNCTION add_digits
(
number INTEGER
) RETURNS INTEGER
BEGIN
DECLARE my_sum INTEGER;
SET my_sum = 0;
SET number = ABS(number);
WHILE (number > 0) DO
SET my_sum = my_sum + (number MOD 10);
SET number = number DIV 10;
END WHILE;
RETURN my_sum;
END //
DELIMITER ;
You could also create a function that works directly on your json sting, parsing it for digits and adding their values.

Special sorting for MySQL result

Is it possible to get MySQL to put a row which matches some condition on the first position?
For instance, say that my result is [1, 3, 5, 6, 7, 1987] and I want it to become [6, 1, 3, 5, 7, 1987] (I want the number 6 to be on the first position)
I feel you are searching for this
SELECT * FROM `pctable`order by colName=6 desc, colName
so colName = 6 will be in top and then for others it will be id wise sort.
Try to use CASE expression in your Order by clause. Such as
ORDER BY CASE WHEN COL_VALUE = 'xxx' THEN '1'
WHEN COL_VALUE = 'xxx' THEN '2'
ELSE COL_VALUE END ASC;
Or with IF in the SELECT somehow:
SELECT IF(number = 6, number, ''), number FROM colname

mysql : turn fraction strings into number

I have strings like... "3/4" and "5/9" and some like... "1/2 km" and "3/4 degree" stored in mysql columns.
I would like to convert them into numbers.
In first case, 3/4 ==> .75.
In more complicated second case, strip off units like "km" and "degree" so
"1/2 km" ==> 0.5.
I think this isn't something you should do in a query, but rather calculate it when it is stored and save the calculated value in the table next to its text value.
But if you want to, you can use some string functions to slice up the value and the do the math yourself:
select
x.Multiplier / x.Divider as Result
from
(select
cast( substr( t.String,
1,
locate('/', t.String) - 1)
as decimal)
as Multiplier,
cast( substr( t.String,
locate('/', t.String) + 1,
locate( ' ',
concat(t.String, ' ')))
as decimal)
as Divider
from
YourTable t) x
Note however, that this may cause trouble if the data is 'invalid'. If it says '0/0 km', it may fail, if it contains 'no data here' it may fail as well.
The above didn't quite work for me so came up with this which does. The query works for '10', '3/4' and '10 3/4'. Obviously you should replace the constructed rows at the bottom with your string or a selected value from a table:
SELECT
IF (
LOCATE(' ',fraction) > 0 OR LOCATE('/',fraction) = 0,
SUBSTRING_INDEX(SUBSTRING_INDEX(fraction,'/','1'),' ','1')
,0
) AS `integer`,
IF (
LOCATE('/',fraction) > 0,
SUBSTRING_INDEX(SUBSTRING_INDEX(fraction,'/','1'),' ','-1'),
0
) AS numerator,
SUBSTRING_INDEX(fraction,'/','-1') AS denominator,
(SELECT `integer`) + ((SELECT numerator) / (SELECT denominator)) AS `decimal`
FROM (
SELECT '10 3/4' AS fraction
UNION SELECT '10'
UNION SELECT '3/4'
) t;
With PHP you could do:
// assuming $vals has the values from the database
$converted = array();
foreach ($vals as $key => $val) {
preg_match("/^(\\d+)\\/(\\d+)/", $val, $matches)
if (count($matches) > 2) {
$numerator = (int) $matches[1];
$denominator = (int) $matches[2];
$converted[$key] = (float) $numerator / $denominator;
}
}