2014-02-17 78 views
4

我有一個表像下面這將具有的產品說明 加入/樞軸項與EAV表

 
╔════╦══════════════╦══════╗ 
║ Id ║ name  ║ price║ 
╠════╬══════════════╬══════╣ 
║ 1 ║ Apple  ║ 23 ║ 
║ 2 ║ shirt  ║ 148 ║ 
║ 3 ║ computer  ║ 101 ║ 
║ 4 ║ printer  ║ 959 ║ 
╚════╩══════════════╩══════╝ 

並且被保持的屬性等由ID

 
╔════╦══════════════╦══════╗ 
║ Id ║ attr_name ║ Value║ 
╠════╬══════════════╬══════╣ 
║ 1 ║ color  ║ red ║ 
║ 1 ║ size   ║ xl ║ 
║ 1 ║ brand  ║ App ║ 
║ 2 ║ color  ║ blue║ 
║ 2 ║ size   ║ l ║ 
║ 3 ║ color  ║ blue║ 
║ 3 ║ size   ║ xxl ║ 
║ 3 ║ brand  ║ HP ║ 
╚════╩══════════════╩══════╝ 

相連接的另一個表如果我知道屬性名稱將僅爲顏色大小和品牌,是否有任何可能的方式來攜帶如下表格:

 
╔════╦══════════╦═══════╦═══════╦══════╦══╗ 
║ id ║ name ║ color ║ brand ║ size ║ ║ 
╠════╬══════════╬═══════╬═══════╬══════╬══╣ 
║ 1 ║ apple ║ red ║ app ║ xl ║ ║ 
║ 2 ║ shirt ║ blue ║  ║ l ║ ║ 
║ 3 ║ computer ║ blue ║ HP ║ XXL ║ ║ 
║ 4 ║ printer ║  ║  ║  ║ ║ 
╚════╩══════════╩═══════╩═══════╩══════╩══╝ 

+0

你真的要合併的表或你想查詢顯示這些值? –

+0

@PatrickHofman我想查詢來獲取這些值,這樣我可以從它創建新表。 – user3199077

+0

此結構的術語是[ 「EAV」](http://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model)。 – user2864740

回答

2

您應該能夠使用聚合函數CASE表達式對行轉換爲列:

select d.id, 
    d.name, 
    max(case when a.attr_name = 'color' then a.value end) color, 
    max(case when a.attr_name = 'brand' then a.value end) brand, 
    max(case when a.attr_name = 'size' then a.value end) size 
from product_description d 
inner join product_attributes a 
    on d.id = a.id 
group by d.id, d.name; 

SQL Fiddle with Demo

由於您使用的是Oracle 11g,那麼你可以使用旋轉功能得到結果:

select id, name, Color, Brand, "Size" 
from 
(
    select d.id, d.name, 
    a.attr_name, a.value 
    from product_description d 
    inner join product_attributes a 
    on d.id = a.id 
) src 
pivot 
(
    max(value) 
    for attr_name in ('color' as Color, 
        'brand' as Brand, 
        'size' as "Size") 
) p; 

SQL Fiddle with Demo