How to select datas that doesnt match in another column

后端 未结 6 1475
花落未央
花落未央 2021-01-23 23:14

So i have this table A:

color        ID       MODEL
-----------------------------
red        | 10   |   HONDA
blue       | 10   |   TOYOTA
red        | 15   |            


        
6条回答
  •  南方客
    南方客 (楼主)
    2021-01-23 23:58

    Use NOT EXISTS to find rows with matching id but different colors:

    select *
    from yourtable a
    where a.color IN ('red', 'blue')
      and not exists (
        select 1
        from yourtable b
        where a.id = b.id
          and b.color NOT IN ('red', 'blue')
        )
    

    Notes:

    • for efficient lookup consider adding indexes ( more distinct values means higher efficiency of tree traversal )
    • consider normalizing your data with additional dictionary color table

提交回复
热议问题