1

i need a simple query which update mysql field with its value and some modification for example if field have value (3,4,5) i can add (,6) and this just in case it have value and if its NULL then update the field with the ","

i searched web and find mysql function called CONCAT and it Returns the string that results from concatenating the arguments.

i tried this one but this didn't work

UPDATE groups SET SubsID = CONCAT(SubsID,",5") WHERE GroupID = 2

it return no issue but 0 rows affected and field not updated

0

4 Answers 4

2
UPDATE GROUPS
SET SubsID = CASE WHEN SubsID IS NULL THEN '6'
                  ELSE CONCAT(SubsID, ',6')
             END
WHERE GroupID = 2
Sign up to request clarification or add additional context in comments.

Comments

1

Add COALESCE before concatenating

UPDATE groups 
SET SubsID = CONCAT(COALESCE(SubsID,''),",5") 
WHERE GroupID = 2

1 Comment

great but when the filed is null it still add the comma i want add the comma only in case the filed is not null otherwise i want add the number only without comma
0

CSV data in a relational database is a terrible idea. Instead, you should use a junction table to store many-to-many relationships between groups and subs.

For example

CREATE TABLE group_to_sub (
    `GroupID` INT NOT NULL REFERENCES `groups` (`GroupID`),
    `SubID` INT NOT NULL REFERENCES `subs` (`SubID`),
    PRIMARY KEY (`GroupID`, `SubID`)
) ENGINE innodb;

INSERT INTO group_to_sub (GroupID, SubID) VALUES (2, 5);

Comments

-2

The query is wrong..Try the below one

UPDATE groups SET SubsID = CONCAT(SubsID,',5') WHERE GroupID = 2;

And make sure that groupid 2 exists

1 Comment

All you've changed is the quotes which don't make a difference in this case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.