1

假设我有下表

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

我想运行一个查询来获取所有只有颜色=蓝色和红色的名称,对于一个qeyry,所有名称的颜色=只有蓝色(没有黑色,没有红色)

我试过类似下面的东西

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

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

谢谢 !

4

2 回答 2

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
于 2012-11-15T03:11:13.810 回答
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
于 2012-11-15T01:27:49.540 回答