1

I have a table activity_types which contains the text for activities e.g.
New project has been assigned to {user} with name {project}
New discussion has been posted by {client} on {project}
Project {project} has been closed by {user}
A draft has been approved by {client} on {project}
and so on

I have another table in which the id of these texts has been populated.

Now my requirement is to fetch these by replacing the text within {} with their actual values like {client} should be replaced with client name, {project} should be replaced with project name.

I have tried using nested replace mysql function but it returns null string. Here is my query

SELECT      REPLACE(REPLACE(REPLACE(att.type_text, '{project}', p.project_business_name), '{user}', u.user_fullname), '{client}', c.client_name) AS activity, a.*
FROM        activities a
LEFT JOIN   activity_types AS att ON att.type_id = a.activity_type
LEFT JOIN   users u ON u.user_id = a.activity_user AND a.activity_user IS NOT NULL
LEFT JOIN   projects p ON p.project_id = a.activity_project AND p.project_is_removed = '0'
LEFT JOIN   clients c ON c.client_id = a.activity_client AND a.activity_client IS NOT NULL;

The problem is that if i replace the c.client_name with static text it works fine but when i replace the static string with c.client_name it return null in activities which does not have {client}. Any guesses where am i doing wrong?

2 Answers 2

1

try adding COALESCE on the column

...,COALESCE(c.client_name, ''),

basically if the column (c.client_name) is null, it will be replace with empty string.

what happens is that when part of the string is replace with null, the whole string becomes null.

Sign up to request clarification or add additional context in comments.

Comments

1

SQL null is contagious. Once you get a null value somewhere and use that null value in functions and derived values, the whole result becomes null. As such, if any of your fields in the REPLACE() chain are null, the whole result becomes null. You can try something like

COALESCE(name_of_field, '')
or
IFNULL(name_of_field, '')

to convert those nulls into an empty string.

Comments

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.