2011-01-11 232 views
0

我只需要一些方向就可以了。我有以下表格:MySQL動態合併/選擇選擇行

Table: entity 
- ID (INT) 

Table: attributes 
- ID (INT) 
- name (VARCHAR) 
- internalname (VARCHAR) 

Table: values 
- ID (INT) 
- entity (ID) 
- attributes (INT) 
- value (Text) 

我要的是做一個選擇statment將返回類似以下內容:

- ID = entity.ID 
- {attributes.internalname ID 1} = values.{attribe internalname 1}.value 
- {attributes.internalname ID 2} = values.{attribe internalname 2}.value 
- {attributes.internalname ID 3} = values.{attribe internalname 3}.value 
- {attributes.internalname ID n} = values.{attribe internalname n}.value 
- etc... 

這就好比結合:

SELECT entity.id FROM entity; 

SELECT (SELECT values.value FROM values WHERE values.entity = entity.ID AND values.attributes = attributes.ID) FROM attributes; 

這是一件很難解釋的事情,但是如果你需要我進一步解釋,請告訴我。

我實際上想要將屬性中的所有值都轉換爲列,並將所有值轉換爲其對應屬性的值,並將ID作爲選擇器。

我給查詢一個ID(元素ID),並在一個結果行中返回所有的數據。

在此先感謝!

+0

我不明白爲什麼表實體存在只有一列,它已存儲在值表 – cfEngineers 2011-01-11 19:29:17

+0

它只是作爲一個索引,並且可能會出現幾列。這實際上與Magento Commerce存儲數據的方式非常相似,問題是他們使用數百個查詢來獲得我試圖在一箇中實現的相同結果。 – Nitroware 2011-01-11 20:52:46

回答

2

您不能動態地創建列,所以你需要事先知道你想要的是什麼列。

如果屬性(1,2,3,4)代表(名字,姓氏,extraname,additionalname),你可以查詢它是這樣的:

select e.id 
     ,v1.value as firstname 
     ,v2.value as lastname 
     ,v3.value as extraname 
     ,v4.value as additionalname 
    from entity e 
    left join values v1 on(e.id = v1.entity and v1.attributes = 1) 
    left join values v2 on(e.id = v2.entity and v2.attributes = 2) 
    left join values v3 on(e.id = v3.entity and v3.attributes = 3) 
    left join values v4 on(e.id = v4.entity and v4.attributes = 4) 
where e.id = ? 

select e.id 
     ,max(case when v.attributes = 1 then value) as firstname 
     ,max(case when v.attributes = 2 then value) as lastname 
     ,max(case when v.attributes = 3 then value) as extraname 
     ,max(case when v.attributes = 4 then value) as additionalname 
    from entity e 
    left join values v on(e.id = v.entity) 
where v.attributes in(1,2,3,4) 
    and e.id = ? 
group by e.id; 

你也可以使用GROUP_CONCAT以一列中的逗號分隔列表形式返回值。

select e.id 
     ,group_concat(v.value) 
    from entity e 
    left join values v on(e.id = v.entity) 
group 
    by e.id; 

哦,而values是保留字。不要用它作爲表名。

呵呵2,除非你真的需要,否則不要使用這個模型。您將在性能和數據一致性方面支付大量的價格。

0

我不會寬恕選擇*因此替換您的列。值可以是一個保留關鍵字

select * 
    from values v 

    left join attributes a 
    on a.id = v.attributes 

    left join entity e 
    on e.id = v.entity 

    where 1=1 

    /* put your where clause here */ 
+0

這非常接近我的意思,但是我希望所有的數據回到一行。我更新了我原來的帖子。 雖然謝謝! – Nitroware 2011-01-11 20:48:02