Selecting records where an array contains a variable

Discussion in 'MySQL' started by egdcltd, Feb 12, 2010.

  1. #1
    A database I'm currently working with has a number of values stored in a comma delimited array due to the way it's getting the data. What I'd like to do, if possible, is to SELECT records where a variable is present in that array.

    eg SELECT * FROM table WHERE (row contains variable)

    So, if the variable is 1, this would get any record where the stored array contains 1, such as (1,3,4) and (1,5,8,9) but not (2,3,6).
     
    egdcltd, Feb 12, 2010 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    SELECT * FROM table WHERE row LIKE (%variable%)

    This is a fairly inefficient way of querying. More importantly storing data like this which is called denormalization is generally not a good way to do so. Databases are meant to store data relationally, where each value in your array would be the value in a column, with a common id attaching it to the parent table.
     
    jestep, Feb 12, 2010 IP
  3. egdcltd

    egdcltd Peon

    Messages:
    691
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hmm, I'm not sure if that would work properly. Wouldn't that return anything with a 1 in it, rather than just 1, eg 1, 10, 11 etc.

    I agree, LIKE is not a good way of querying the database. Unfortunately, I don't know how to store the data in a better format, as I'm receiving it in an array of variable length.
     
    egdcltd, Feb 12, 2010 IP
  4. koko5

    koko5 Active Member

    Messages:
    394
    Likes Received:
    14
    Best Answers:
    1
    Trophy Points:
    70
    #4
    @egdcltd , you need this ;)
     
    koko5, Feb 13, 2010 IP
  5. egdcltd

    egdcltd Peon

    Messages:
    691
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    0
    #5
    I hadn't known of that, thanks, I'll take a look at it.
     
    egdcltd, Feb 15, 2010 IP