从组合sql的多个值中选择一个值

从组合sql的多个值中选择一个值,sql,join,Sql,Join,我们的id表如下所示 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 | nul

我们的id表如下所示

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有多个FIDED时,我们将它们视为NULL与REF表

连接。 对于所有newsecid,不需要结合newsecid和featid从ref表中获取oldsecid,因为在newsecid为6、2和3且featid为null的情况下,始终只有一个值

但仅对于newsecid 1,16,25,26,我们必须从ref表中的newsecid和featid组合中选择oldsecid,因为有两个值。一个值为null 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
使用这个,我从ref表中得到oldsecid 2,6,5,因为只有一个值

对于使用上述查询的情况1、16、25、26,我得到的是随机oldsecid。在这里,我需要featid不为null的oldsecid

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


任何帮助

根据我的理解,请尝试:

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)

Id
是一个可怕的表名…@jarlh:举个例子