2012-03-10 55 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')