How to select datas that doesnt match in another column

后端 未结 6 1430
花落未央
花落未央 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:41

    I think your expected result should just be red 15. Red 30 would not qualify because of yellow 30, which shares the same id. Check out my code:

    SELECT t.id, t.color
    FROM t
    INNER JOIN
    (SELECT id
     FROM t
     GROUP BY id
     HAVING COUNT(*) = 1) sub
    ON t.id = sub.id
    WHERE color = 'red'
    OR color = 'blue'
    
    0 讨论(0)
  • 2021-01-23 23:42

    This query returns all the IDs where the COLOR is red or blue but not both.

    select id , color
    from  your_table 
    where color in ('red', 'blue')
    and id in (
        select id 
        from   your_table 
        where color in ('red', 'blue')
        group by id 
        having count(*) = 1) 
    
    0 讨论(0)
  • 2021-01-23 23:48

    Something like this

    SELECT * 
    FROM   yourtable 
    WHERE  id IN (SELECT id 
                  FROM   youtable 
                  GROUP  BY id 
                  HAVING Count(case when color IN ( 'red', 'blue' ) then 1 end) = 1) 
    
    0 讨论(0)
  • 2021-01-23 23:50

    or using an anti join

    select t1.color, t1.id 
    from 
        tableA t1
    left outer join 
         tableA t2 on t2.id = t1.id and t2.color != t1.color 
    where 
     t1.color in ('red', 'blue')
    and t2.color is null
    
    0 讨论(0)
  • 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
    0 讨论(0)
  • 2021-01-24 00:05

    Removed the previous answer. Tested this and it is working.

    WITH tbl
    AS (SELECT
      color,
      id
    FROM TABLE1
    WHERE color IN ('red', 'blue')
    )
    SELECT
      t1.color,
      t1.id
    FROM tbl t1
    LEFT JOIN tbl t2
      ON t1.id = t2.id
      AND t1.color <> t2.color
    WHERE t1.id IS NULL
    OR t2.id IS NULL
    
    0 讨论(0)
提交回复
热议问题