【问题标题】:Join own table to select values加入自己的表以选择值
【发布时间】:2012-03-27 11:15:46
【问题描述】:

我有这样的看法

id     name     characteristic     value     isList
1      cube         sides           6          0
1      cube         color          blue        0
2    triangle       sides           3          0
3    hexagon        (null)        (null)     (null)
4    rectangle      weight          15         0

我需要选择所有 ID 和名称并检索一些特征和相应的值。例如,我想检索所有图形(id 1、2、3 和 4)以及特征边和颜色(如果可用,如果不可用,则仅填充 id 和 name;其他为 null)。

我试过了

select *
from shapes_view
where (id = 1 or id = 2 or id = 3 or id = 4) and (characteristic like 'sides' or characteristic like 'color')

但很明显,它会检索 id 1 和 2,而不是 3 和 4。

我的猜测是我需要某种子查询来执行此操作,但是当我尝试将这个视图与其自身连接时,我会得到一长串的组合,这些组合与我需要的任何地方都不相近。

我打算得到的是类似的东西

id     name     characteristic     value     isList
1      cube         sides           6          0
1      cube         color          blue        0
2    triangle       sides           3          0
3    hexagon        (null)        (null)     (null)
4    rectangle      (null)        (null)     (null)

我知道我可以选择所有值并排除我在 java 端不做什么,但这听起来不太正确...

谁能帮我解决这个问题? 最好的问候

【问题讨论】:

    标签: sql oracle select join view


    【解决方案1】:

    您可以使用自联接——实际上,是几个自联接

    select all_ids.id,
           all_ids.name,
           s.value sides,
           c.value color
      from shapes_view all_ids
           left outer join (select *
                              from shapes_view
                             where characteristic = 'sides') s
                   on( s.id = all_ids.id )
           left outer join (select *
                              from shapes_view
                             where characteristic = 'color') c
                   on( c.id = all_ids.id )
    

    或者您可以旋转数据

    select id,
           name,
           max( case when characteristic = 'sides'
                     then value
                     else null
                  end) sides,
           max( case when characteristic = 'color'
                     then value
                     else null
                  end) color
      from shapes_view
     group by id, name
    

    为 N 个不同属性提取数据所需的查询的复杂性是这种非常通用的实体-属性-值数据模型通常不受欢迎的原因之一。

    【讨论】:

      【解决方案2】:

      也许我遗漏了一些东西,但听起来这就是你所需要的:

      select
        name,
        characteristic,
        case when characteristic in ('sides','color') then value else null end as value,
        case when characteristic in ('sides','color') then isList else null end as isList
      from shapes_view
      where id in (1,2,3,4)
      and characteristic in ('sides','color')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-24
        • 2020-01-10
        • 1970-01-01
        • 2018-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多