【问题标题】:Pick one value from multiple value from the combination sql从组合sql中的多个值中选择一个值
【发布时间】:2017-09-15 12:03:21
【问题描述】:

我们有如下的id表

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

单个 id 将有单个 newsecid

另一张桌子很棒

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

一个id可以有多个feat 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 时,我们认为它们为null 以加入参考表

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

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

我使用的组合没有要求的情况

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,因为我不仅仅只有这些情况。

任何帮助

【问题讨论】:

  • Id 是一个可怕的表名...
  • @jarlh : 仅作为示例

标签: sql join


【解决方案1】:

根据我的理解,试试:

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)

【讨论】:

    猜你喜欢
    • 2017-02-05
    • 2016-05-18
    • 2012-12-01
    • 1970-01-01
    • 2020-05-27
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多