从组合sql

时间:2017-09-15 12:03:22

标签: sql join

我们有id表如下

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

单个ID将具有单个newsecid

其他表格是壮举

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

一个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存在多个featid时,我们将它们视为null以与ref表连接

对于所有newsecids,不需要newsecid和featid的组合来从ref表中获取oldsecid,因为总是只有一个值,例如newsecids为6,2和3,featid为null。

但是对于newsecids 1,16,25,26,我们必须从ref表中选择oldsecid和featid的组合中的oldsecid,因为有2个值。具有null featid和一个具有一些featid值的值。 / p>

不需要我正在使用的组合

的情况
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。在这里我需要oldsecid,其中featid不为空。

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

任何帮助

1 个答案:

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