Search code examples
mysqlwhere-in

mysql - count of all instances of multiple strings


Let's say there is a table of tie-dye t-shirts for example... Some shirts have multiple colors, listed as a string, comma separated. Such as blue,yellow,red,purple or green,white,black,red.

I would like to do one query to get a count of how many times each color is present. I will know beforehand which 'colors' will exist in the column.

What I'm doing now is a separate query for each 'color':

SELECT count(color) WHERE color LIKE '%blue%'
SELECT count(color) WHERE color LIKE '%red%'
SELECT count(color) WHERE color LIKE '%yellow%'

etc.....

Is there a more efficient way of doing this than 15 different queries?

Example: If my table were to have values for the column 'color' of "blue, red, yellow", and another row will be color="red, green, yellow" etc...

I'm looking for a query that will return:

Blue    Red   Yellow  Green
  1      2      2       1

Solution

  • Assuming your assertion I will know beforehand which 'colors' will exist in the column, what you are looking for is:

    SELECT
        SUM(color like '%blue%') as total_blue,
        SUM(color like '%red%') as total_red,
        (...)
        SUM(color like '%yellow%') as total_yellow
    FROM
        your_table;
    

    The SUM(any boolean condition you want) is a really nice trick to remember.