0

I have data stored in a column called supervisors_id in a table. The structure of data in this column is like this: 12, 44, 55, 32, 85, 75, 45. So I want to fetch the total number of ID's in that supervisors_id column in a row. My expected result, for instance in the above example should be 7. How can I do that with a MySQL query ?

2
  • what is the column type of supervisors_id? did you try anything yet to solve this? Commented Sep 9, 2018 at 12:54
  • The column type for supervisors_id is text Commented Sep 9, 2018 at 13:06

1 Answer 1

2

You can count the commas by comparing the length of the string to the length of the string with commas replaced by the empty string.

Somewhat like:

SELECT length(supervisors_id) - length(replace(supervisors_id, ',', '')) + 1
       FROM elbat;

If there are also empty strings in the column you might need to add some more logic, that checks for that and returns 0 instead of 1 in that case. For example by using a CASE:

SELECT CASE
         WHEN supervisors_id <> '' THEN
           length(supervisors_id) - length(replace(supervisors_id, ',', '')) + 1
         ELSE
           0
       END
       FROM elbat;

But your design is not the best. Instead of a comma delimited list, there should be a linking table.

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

5 Comments

Thanks man, it worked like magic!! Could you just give me a hint of how using it with a linking table would work. I'm just trying to avoid very long rows in a table, but i'm open to new ideas.
@PhilipOnyango: Welcome! Have a new table, that stores a (as in one) supervisor ID per row and the ID of a row of that other table. I cannot go into more detail as you haven't revealed that much of your schema.
I already have a parent table for all the supervisors. So in this table called daily_tasks, I'm simply concatenating a supervisor's ID whenever a supervisor is assigned a task on that day.
@PhilipOnyango: Instead of doing that create another table and insert the supervisors ID and the task ID into it.
I've now fully gotten your point. I think it's a better implementation of my situation. Muchas gracias, I appreciate.

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.