从组合SQL中选择一个值

  • 本文关键字:一个 组合 SQL 选择 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         |  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有多个功能时,我们将其视为null与ref表一起加入

对于所有Newsecids,Newsecid和Featid的组合都不需要从参考表中获取OldSecid,因为在NewsEcids中,总是只有一个值为6,2和3,而feat In teat is n ull则只有一个值。

,但对于只有1,16,25,26的新闻固定,我们必须从参考桌上的新闻和壮举的组合中挑选oldsecid,因为它有2个值。/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

使用此信息,我从参考表中获得了旧的2,6,5,因为只有一个值。

对于使用上述查询的1,16,25,26,我会随机oldsecid。

我们可以以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)

最新更新