如何选择只有一个值的行?

时间:2013-02-26 17:03:33

标签: mysql select

这就是我的表格:

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

我只需要独占 color =“Red”的行。
它必须返回“a”(“b”也包含值“Blue”)。

如何设置选择?

2 个答案:

答案 0 :(得分: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 with Demo

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

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

请参阅SQL Fiddle with Demo

答案 1 :(得分:2)

尝试他的查询

Select * 
from tbl 
where color = 'RED' AND USER not in 
(Select USER from tbl where color <> 'RED');