Tuesday, April 12, 2011

A fun little MySQL puzzle

I was looking for a way to convert a column in the database that has things like this: M1.1 and M1.2 all the way up to M1.15 into something like this:
M1.01 and M1.02 all the way up to M1.09 and M1.1 (for 10) and M1.15 for any above 10.

I used mysql like this
SELECT item as `the item to fix`,
SUBSTRING_INDEX(item,'.',1) as `the part to the left of the period`,
SUBSTRING_INDEX(item,'.',-1) as `the part to the right of the period`,
if(SUBSTRING_INDEX(item,'.',-1) < 10,
CONCAT(SUBSTRING_INDEX(item,'.',1),'.','0',SUBSTRING_INDEX(item,'.',-1))
,
if(SUBSTRING_INDEX(item,'.',-1) = 10,
CONCAT(SUBSTRING_INDEX(item,'.',1),'.',1)
,
item
)
) as `the fixed value`
FROM `data` where item like '%.%'


SUBSTRING_INDEX gets the text to the left of the first occurrence of the '.' if you use a 1 for the 3rd parameter and it gets the text to the right of the last occurrence of the '.' if you set the 3rd parameter to a -1.
Cool little puzzle that took 10 minutes to solve.

No comments: