sql查询完全匹配

时间:2012-11-15 01:24:18

标签: sql

假设我有下表

name | color
-------------
jon    blue
jon    black
jon    red
bill   blue
bill   red
jack   blue
....

我想运行查询以获取只有colors = blue和red的所有名称 和所有名字的qeyry一样,color =只有蓝色(没有黑色,没有红色)

我尝试了类似下面的内容

select name, color from table where color in ('blue', 'red')
group by name, color

但它给了我比我预期的更多结果...... 有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

  select name
    from tbl
   where color in ('blue','red')
     and not exists (select * from tbl t2
                     where t2.name=tbl.name and t2.color NOT IN ('blue','red'))
group by name
  having count(distinct color) = 2

答案 1 :(得分:0)

试试这个问题:

SELECT name, color
FROM table1
WHERE name IN
(
    SELECT name
    FROM table1 t1
    WHERE color IN ('blue', 'red')
      AND NOT EXISTS
      (
         SELECT * 
         FROM table1 t2 
         WHERE t1.name = t2.name
           AND t2.color NOT IN ('blue', 'red')
       )
    GROUP BY name
    HAVING COUNT(DISTINCT color) = 2 --to be sure only red won't be accepted

    UNION

    SELECT name
    FROM table1 t1
    WHERE color = 'blue'
     AND NOT EXISTS
     (
        SELECT * 
        FROM table1 t2 
        WHERE t1.name = t2.name
          AND t2.color <> 'blue'
     )
)
ORDER BY name, color
相关问题