2017-09-15 44 views
-1

我们有ID表如下从组合SQL选择从多值一个值

id | newsecid 
--- | --- 
1 | 10 
2 | 20 
3 | 30 

单ID将有单newsecid

其他表的壮举

id | featid 
--- | --- 
1 | 5 
1 | 6 
2 | 2 
2 | 4 

一个ID可以有多个专长ID

参考表

newsecid | featid | oldsecid 
---  | ---  | --- 
6   | null | 2 
2   | null | 6 
3   | null | 5 
1   | NULL | 1 
1   | 5  | 4 
16  | NULL | 16 
16  | 4  | 13 
25  | NULL | 26 
25  | 6  | 25 
26  | NULL | 26 
26  | 6  | 24 

当有对同一ID的多个featids的,我们把它们看成空与裁判桌

对于所有newsecids加入没有必要的newsecid组合和featid得到oldsecid从ref表中,因为总是只有一个值,比如在newsecids的情况下,6,2和3的featid为null。

但是,对于只有newsecids 1,16,25,26,我们必须从ref表中的newsecid和featid的组合中选择oldsecid,因为有2个值。一个为空featid,另一个为一些featid值。

其中对于组合没有要求我使用

select c.oldsecid from id i 
inner join feat f on i.id=f.id 
inner join ref c on i.newsecid = c.newsecid 

使用这个我从裁判表中获取oldsecid 2,6,5由于只有一个值的情况下。

对于使用上述查询的情况1,16,25,26,我得到了随机的oldsecid。在此我需要那个fesetid不为null的oldsecid。

我们可以将newsecid的条件硬编码为1,16,25,26,因为我不只有这些情况。

任何帮助

+1

'Id'是一个可怕的表名... – jarlh

+0

@jarlh:就一个例子 – Remon

回答

0

按我的理解,尝试:

select c.oldsecid from id i 
inner join feat f on i.id=f.id 
inner join ref c on i.newsecid = c.newsecid 
Inner join(select newSecId,count(*) as newSecIdCount from ref group by newSecId) r on r.newSecId=i.newSecId 

Where (r.newSecIdCount=1 or c.feetid is not null)