I have new problem with query:
I want to update column ‘column’ depending on id with some new data:
UPDATE table SET column = CASE
WHEN id = 2 THEN CONCAT(`column`, ',7')
WHEN id = 3 THEN CONCAT(`column`, ',10')
ELSE column
END;
Unfortunatelly, adding new values to column must have a comma at the beginning because column stores data as comma separated values.
For example it looks like this:
id | column
-------------
2 | 3, 1, 20
3 | 1, 5
After executing a query I get:
id | column
-------------
2 | 3, 1, 20, 7
3 | 1, 5, 10
It’s all good till now. Unfortunatelly if I update column that is empty it all starts with comma and it looks like this:
id | column
-------------
2 | ,7
3 | ,10
It causes some problems when grabing data from db becuase when i explode() it, it makes first array value empty. I want to remove such first commas when updating table.
I guess I should make some ‘if’ statements that check length of ‘column’ (with char_length) and if it’s empty update without first, starting comma.
Can you help me with proper syntax?
Summary:
How to make proper query that updates column as described above with values starting with comma if ‘column’ exists. If ‘column’ is empty update it with variable without starting comma.
How about this:
MySQL’s reference manual: CHAR_LENGTH(..) and IF(..,..,..).