Query with multiple values in a column

后端 未结 4 1248
忘了有多久
忘了有多久 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: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'
     )
    

提交回复
热议问题