0

对不起标题不好的帖子。

假设我有下表:

C1 | C2       | c3
1  | foo      | x
2  | bar      | y
2  | blaz     | z
3  | something| y
3  | hello    | z
3  | doctor   | x
4  | name     | y
5  | continue | x
5  | yesterday| z
6  | tomorrow | y

我正在尝试使用执行以下联合的 sql 语句:第一次检索检索所有记录 w/c3 = 'y'

第二次检索检索记录的第一个实例,其中 c3 <> 'y' 并且结果不在前一个联合中

所以,对于结果,我应该看到:

C1 | C2   
1  | foo  
2  | bar 
3  | something
4  | name
5  | continue
6  | tomorrow    

所以有两个问题:1:我是否完全在我认为可以做到这一点的地方吸烟,以及 2:(假设我可以),我该怎么做?

4

3 回答 3

1

试试这个:

SELECT   a.C1, a.C2
  FROM   MyTable a
 WHERE   a.C3 = 'y'
    UNION
SELECT   b.C1, b.C2
  FROM   MyTable b
 WHERE   b.C3 <> 'y' AND
         b.C1 not in 
            (
               SELECT c.C1
                 FROM MyTable c
                WHERE c.C3 = 'y'
            )

更新 1

顺便问一下,为什么你想要的结果中只有一个记录5?实际上,可能有两个.

观看演示 ​​1

或者

SELECT g.C1, MIN(g.C2) C2
FROM
(SELECT   a.C1, a.C2
  FROM   MyTable a
 WHERE   a.C3 = 'y'
    UNION
SELECT   b.C1, b.C2
  FROM   MyTable b
 WHERE   b.C3 <> 'y' AND
         b.C1 not in 
            (
               SELECT c.C1
                 FROM MyTable c
                WHERE c.C3 = 'y'
            )
) g
GROUP BY g.C1 

SEE FOR DEMO 2(产生与您想要的结果相同的结果)

于 2012-07-18T00:43:10.977 回答
1

演示@Sql 小提琴

select *
  from table1
 where c3 = 'y'
 union all
(select table1.*
  from table1
  left join table1 t1
    on table1.c1 = t1.c1
   and t1.c3 = 'y'
 where table1.c3 <> 'y'
   and t1.c1 is null
 -- The meaning of first becomes clear here
 order by table1.c3, table1.c2
 limit 1)

注意: foo 不在列表中,因为它被标记为x.

于 2012-07-18T00:45:26.173 回答
1

试试这个:

    SELECT C1, C2
    FROM   Table1
    Where  C3 = 'y'

    UNION

   (
    SELECT  C1, C2
    FROM  Table1
    Where C3 <> 'y' ORDER BY C1 LIMIT 1
   )
 ORDER BY C1
于 2012-07-18T00:50:56.660 回答