4

这是我的桌子的样子:

╔══════╦═══════╗
║ USER ║ COLOR ║
╠══════╬═══════╣
║ a    ║ Red   ║
║ b    ║ Blue  ║
║ c    ║ Blue  ║
║ b    ║ Red   ║
║ a    ║ Red   ║
║ c    ║ White ║
╚══════╩═══════╝

我只需要只有颜色=“红色”的行。
它必须返回“a”(“b”也包含值“Blue”)。

如何设置选择?

4

2 回答 2

3

您可以使用:

select *
from yourtable t1
where color = 'red'
  and exists (select user
              from yourtable t2
              where t1.user = t2.user
              group by user
              having count(distinct color) = 1)

请参阅带有演示的 SQL Fiddle

或者没有子查询,您可以使用:

select *
from yourtable
group by user
HAVING  SUM(color = 'red') = COUNT(*)

请参阅带有演示的 SQL Fiddle

于 2013-02-26T17:06:18.607 回答
2

尝试他的查询

Select * 
from tbl 
where color = 'RED' AND USER not in 
(Select USER from tbl where color <> 'RED');
于 2013-02-26T17:07:26.010 回答