2012-03-10 84 views
0

我有这样一个加入自己的表来选择值

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和名称;其余为空)。

我试图

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

但是,很明显,检索IDS 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方面,但它听起来不是很正确...

任何人都可以帮助我吗? 最好的问候

回答

1

您可以使用自join--实际上,一对夫妇自加入

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个不同属性的数据是这种非常通用的实体属性值数据模型通常被忽视的原因之一。

0

也许我失去了一些东西,但听起来好像这是你所需要的:

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')