Query a comma seperated list of values in field

Discussion in 'MySQL' started by Omzy, Jan 3, 2009.

  1. #1
    Basically I have a field calls 'tags' in my Customer table. Initially this was just a straightforward field containing just one value, but now I would like it extend it to include multiple values seperated by a comma.

    I'm using PHP and MySQL and this is the current code:

    SELECT * FROM customer WHERE (tags='$tags')
    Code (markup):
    How do I now get it to match the value of $tags to any records that have that value in the 'tags' field?
     
    Omzy, Jan 3, 2009 IP
  2. crivion

    crivion Notable Member

    Messages:
    1,669
    Likes Received:
    45
    Best Answers:
    0
    Trophy Points:
    210
    Digital Goods:
    3
    #2
    SELECT * FROM customer WHERE tags LIKE '%tags%'
    or
    SELECT * FROM customer WHERE tags LIKE 'tags'
     
    crivion, Jan 3, 2009 IP
  3. Omzy

    Omzy Peon

    Messages:
    249
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Cheers mate,

    The first one worked, the second one didn't.

    :)
     
    Omzy, Jan 3, 2009 IP
  4. crivion

    crivion Notable Member

    Messages:
    1,669
    Likes Received:
    45
    Best Answers:
    0
    Trophy Points:
    210
    Digital Goods:
    3
    #4
    :) glad to help you
     
    crivion, Jan 3, 2009 IP
  5. mwasif

    mwasif Active Member

    Messages:
    816
    Likes Received:
    23
    Best Answers:
    1
    Trophy Points:
    70
    #5
    You should use FIND_IN_SET() instead of LIKE. Using LIKE may not return the correct results e.g.
    SELECT * FROM customer WHERE tags LIKE '%ball%'
    Code (markup):
    will return ball, balls and ballon, ballons. I hope you dont want to get the results of ballons.

    But the using FIND_IN_SET() will give you the correct results.
    SELECT * FROM customer WHERE FIND_IN_SET('ball',tags)
    Code (markup):
     
    mwasif, Jan 3, 2009 IP
  6. phper

    phper Active Member

    Messages:
    247
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #6
    I'd put the list in a separate table with 'customer_id' and 'tag' fields in it instead, as such substring comparison is very slow.

    Also, the sample query given above would return tags like 'ballet', 'baseball', 'fishballs', etc. To correctly match only 'ball', you'd have to do 4 comparisons (which, again, is very slow):
    [B]SELECT * FROM customer WHERE [/B]
      [B]tags = 'ball'[/B] [I]-- this is the only tag[/I]
      [B]OR tags LIKE 'ball,%'[/B] [I]-- the tag occurs first[/I]
      [B]OR tags LIKE '%,ball,%'[/B] [I]-- the tag occurs in the middle[/I]
      [B]OR tags LIKE '%,ball'[/B] [I]-- the tag occurs last[/I]
    Code (markup):
     
    phper, Jan 4, 2009 IP