Home  >  Q&A  >  body text

Query values ​​in comma separated string in MySQL

<p>I have a field <code>COLORS (varchar(50))</code> in my table <code>SHIRTS</code> which contains a comma separated string like < ;code>1,2,5,12,15,</code>. Each number represents an available color. </p> <p>When running the query <code>select * from shirts where colors like '%1%'</code> to get all shirts that are red (color=1), I also get the color is gray (= 12) and orange (=15) shirts. </p> <p>How should I rewrite the query so that it only selects all colors with the color 1 instead of all colors containing the number 1? </p>
P粉763748806P粉763748806451 days ago433

reply all(2)I'll reply

  • P粉036800074

    P粉0368000742023-08-18 10:38:23

    FIND_IN_SET is your friend in this case

    select * from shirts where FIND_IN_SET(1,colors)

    reply
    0
  • P粉254077747

    P粉2540777472023-08-18 00:12:51

    The classic method is to add commas on the left and right sides:

    select * from shirts where CONCAT(',', colors, ',') like '%,1,%'

    But find_in_set can also be used:

    select * from shirts where find_in_set('1',colors) <> 0

    reply
    0
  • Cancelreply