2014-10-28 26 views
0

我在使用ARForms插件捕獲名稱,電子郵件和電話號碼的WordPress站點中有一個表單,但是在一個愚蠢的數據庫佈局中。MySQL數據透視表中的列在他們自己的行中

我有一個MySQL的WordPress表是這樣的:

|id   |entry_value  |field_id  |entry_ID  | 
|1   |John    |74    |1    | 
|2   |Smith    |75    |1    | 
|3   |555 1234   |76    |1    | 
|4   |[email protected] |77    |1    | 
|5   |Sue    |74    |2    | 
|6   |Brown    |75    |2    | 
|7   |555 4321   |76    |2    | 
|8   |[email protected] |77    |2    | 

我使用另一個插件導出報表,試圖查詢該表,並得到誰已經填寫了表格的所有用戶的報告。

我想在這樣的格式:

|ID   |Name    |Surname   |Email   |Telephone 
|1   |John    |Smith   |[email protected] |555 1234 
|2   |Sue    |Brown   |[email protected] |555 4321 

我試圖從看幾個例子如下,但我不斷收到NULL的返回。我需要以某種方式將其過濾出來,並且只在有值的地方進行轉換。注意:有2個額外的領域相比,上面的例子中,InterestedIn和省:

create view users_subscribed as (
    select 
    a.entry_id, 
    a.field_id, 
    case when field_id = '74' then entry_value end as FirstName, 
    case when field_id = '75' then entry_value end as LastName, 
    case when field_id = '76' then entry_value end as Email, 
    case when field_id = '78' then entry_value end as Phone, 
    case when field_id = '79' then entry_value end as InterestedIn, 
    case when field_id = '81' then entry_value end as Province 
    from ch_arf_entry_values a 
); 

create view users_subscribed_extended_pivot as (
    select 
    entry_id as ID, 
    FirstName, 
    LastName, 
    Email, 
    Phone, 
    InterestedIn, 
    Province 
    from users_subscribed 
    group by entry_id 
); 


SELECT * FROM users_subscribed_extended_pivot ; 

誰能請幫助...

+0

MAX(CASE WHEN ... END)姓名...等... GROUP BY entry_id,FIELD_ID - 和引號是不必要 – Strawberry 2014-10-28 14:37:43

回答

1

你缺少,GROUP BY和MAX聚合函數

你不需要兩種觀點,你可以做到這一點,在一個視圖

select 
    a.entry_id, 
    MAX(case when field_id = 74 then entry_value end) as FirstName, 
    MAX(case when field_id = 75 then entry_value end) as LastName, 
    MAX(case when field_id = 76 then entry_value end) as Email, 
    MAX(case when field_id = 78 then entry_value end) as Phone, 
    MAX(case when field_id = 79 then entry_value end) as InterestedIn, 
    MAX(case when field_id = 81 then entry_value end) as Province 
    from ch_arf_entry_values a 
    GROUP BY a.entry_id 
+0

謝謝,完美的作品:) – 2014-10-29 06:12:37