PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, March 17, 2022

[FIXED] get count number of values with comma seprated

 March 17, 2022     mysql, phpmyadmin, sql     No comments   

Issue

I have a column in SQL which is a comma separated list (ie cats,dogs,cows,) I need to count the number of cats,dogs and cows in it using only mysql

id | Name
1  | dog,cat
2  | cow,cat
3  | dog,cat,cow

Solution

You first effort should go into fixing your data model. You should have a separate table to store the id/name relationships, where each tuple would be stored on a separate row, like:

id    name
----------
1     dog
1     cat
2     cow
2     cat
3     dog
3     cat
3     cow

This would make your queries much simpler and more efficient.

As of your current set up: if the list of values is fixed, you can use find_in_set() and conditional aggregation:

select
    sum(find_in_set('cat', name) > 0) no_cats
    sum(find_in_set('cow', name) > 0) no_cows,
    sum(find_in_set('dog', name) > 0) no_dogs
from mytable


Answered By - GMB
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing