SQL查询 - 如果存在,则选择一个其他,从不两者

时间:2012-08-27 21:41:17

标签: sql

假设有一个表格有两列,名字和眼睛颜色。

在此表中,您可能有:

Name - Green Eyes
Name - Brown Eyes

我正在尝试为绿眼睛的名字选择所有行,但如果有一个没有绿眼睛的名字,那么我想选择棕色眼睛的名字。我永远不想为给定的名称返回两行。有关如何做到这一点的任何想法?任何帮助将不胜感激!

5 个答案:

答案 0 :(得分:3)

SELECT COALESCE(g.name, b.name) name,
    COALESCE(g.eye_color, b.eye_color) eye_color

FROM (
  SELECT DISTINCT name, eye_color
  FROM eye_colors
  WHERE eye_color = 'green'
) g

FULL OUTER JOIN (
  SELECT DISTINCT name, eye_color
  FROM eye_colors
  WHERE eye_color = 'brown'
) b
ON b.name = g.name

答案 1 :(得分:1)

IF EXISTS(SELECT * FROM Table WHERE Color='Green')
    SELECT * FROM Table WHERE Color = 'Green'
ELSE
    SELECT * FROM Table WHERE Color='Brown'

答案 2 :(得分:0)

我愿意

select * 
from person 
where person.eyecolor = 'green' 
   or (     person.eyecolor = 'brown' 
        and not exists(select null from person where person.eyecolor = 'green')
      )

答案 3 :(得分:0)

我会在表格的(名称,颜色)上有一个索引,然后加入到自身,但先取“绿色”,然后再找棕色

select
      justName.Name,
      coalesce( Green.Eye_Color, Brown.Eye_Color ) as Eye_Color
   from
      ( select distinct name 
           from eye_colors ) justName
         left join eye_colors as Green
            on justName.Name = Green.Name
           and Green.Eye_Color = 'Green'
         left join eye_colors as Brown
            on justName.Name = Brown.Name
           and Brown.Eye_Color = 'Brown'

预查询只获得不同的名称,然后通过左连接到表两次,一次为绿色,第二次为棕色。如果绿色记录不匹配,则会获得棕色实例。

答案 4 :(得分:0)

select *
from person p
inner join (
    select decode(count(name), 1, 'Green Eyes', 'Brown Eyes') as color
    from person
    where color = 'Green Eyes'
    and rownum < 2
) t
on p.color = t.color

如果至少有一个人带有“ Green Eyes”,则子查询应返回“ Green Eyes”,否则将返回“ Brown Eyes”。代替内部联接,我们可以使用where子句进行过滤。