Query with multiple values in a column

后端 未结 4 1261
忘了有多久
忘了有多久 2020-11-22 03:14

I have a table like:

id     name            children
1      Roberto         Michael,Dia
2      Maria           John,Alex
3      Mary            Alexandre,Dia         


        
相关标签:
4条回答
  • 2020-11-22 03:31

    The best solution would be to normalize your schema. You should have a separate table with one row for each child, instead of a comma-delimited list. Then you can join with this table to find parent with a specific child. See @themite's answer for an example of this.

    But if you can't do that for some reason, you can use FIND_IN_SET:

    WHERE FIND_IN_SET('Alex', children)
    
    0 讨论(0)
  • 2020-11-22 03:40

    That's why you'd want to have two tables here.

    parents:
    id  name
    1   Roberto  
    2   Maria
    3   Mary
    
    children:
    id  parentid name
    1   1        Michael
    2   1        Dia
    3   2        John
    4   2        Alex
    5   3        Alexandre
    6   3        Diana
    

    And now you can query this much more effectively with a join or an exists:

    SELECT *
    FROM Parents
    WHERE EXISTS(
        SELECT * 
        FROM Children 
        WHERE parentid=Parents.id 
          AND Children.name='Alex'
     )
    
    0 讨论(0)
  • 2020-11-22 03:45

    I would rather make different tables for children and parents something like this.

    Table for parents

    parent_id     name            
    1             Roberto         
    2             Maria           
    3             Mary     
    

    Table for children

    children_id  parent_id  name
    1            1          Michael     
    2            1          Dia 
    3            2          John
    

    .... and so on

    0 讨论(0)
  • 2020-11-22 03:46

    You should split the data into two tables.

    the first would look like this

    ID    Name
    1     Roberto
    2     Maria
    3     Mary
    

    And the second like this

    ParentId     child
    1            Michael
    1            Dia
    2            John
    2            Alex
    

    and so on.

    then you could do the query you want without having to worry about like and your data is much more useable

    0 讨论(0)
提交回复
热议问题