Reputation: 1
I have a table T with a few columns out of which 1 column is having comma separated values. I want to process this column and update for all rows in the following manner
the column contains values like "15,20"; "30,15,50" (not in sorted order). And there are only 10 distinct possible values
Split the column based on delimeter (,) Find the max value in the resulting list. Based on max value, update the column with a specific value.
I am new to Mysql scripting. So, it would be helpful if you can give some pointers of how this can be solved
Upvotes: 0
Views: 375
Reputation:
This guy here selects the biggest number from the list (you can run this code from a mySQL UI immediate/query window or command line to test):
SET @foo = CONCAT('SELECT ', REPLACE('40,50,10,20', ',', ' UNION ALL SELECT '));
SET @foo = CONCAT('SELECT * FROM (', @foo, ' ORDER BY 1 DESC) AS uncleFoo LIMIT 1');
PREPARE STMT FROM @foo;
EXECUTE STMT;
DEALLOCATE PREPARE STMT;
UPDATE myTable SET myField=[value from above @foo execution] WHERE [your clause]
Upvotes: 0
Reputation: 64399
Apart from the fact that I am convinced that this is not the way to do it, there is a way. But I cannot stress enough that the database-design is a problem, and the descision to do this logic in the sql as well. This should not be.
Please, don't do this. Having said that...
You need this, I think to understand from your question:
The first is the hardest. See for instance this question about exploding and the mysql manual for string functions (especially the comments). It can be done, but you need to do some trickery, and using your knowledge about the limits on your string (the amount, the way they are formed etc) you can probably do something hackish using SUBSTRING_INDEX
like in those examples.
If you have the separate values, you can compare them to find the highest one. You might be able to use the sql MAX
function, but it might be quicker to do comparisons when you're doing all the substring-split-explode hacking anyway.
Now you have a value, you can either use some sort of CASE
statement to hardcode effects, or enter it in a query.
The database design looks wrong, but it could be a valid reason. There could also be limits on what you can change (e.g. it is not your database), so a given is a given. Sad but true.
The fact that you need to do this in sql, I'm having a harder time with that. There should be someone who has a reason to want this, and that someone is probably wrong. Could you go to this person and figure out what the reason is?
Upvotes: 1