2016-01-06 53 views
0

我需要創建一個SQL視圖(使用MySQL Workbench),該視圖應該只取一行的所有值,並將它們與第一列上各自的列名稱堆疊在一起。就像這樣:如何創建2列SQL視圖?

原始表:

name    | email    | address   | country | ... 
------------------|----------------------|--------------------|------------| 
Al Wade Avery  | [email protected]  | 1004 Court Street | USA  | 
Antone Clay  | [email protected]  | 6219 Devon Court | UK   | 
Issac Luigi  | [email protected] | 43 Bridge Street | USA  | 
Lucio Andrea  | [email protected] | 2283 Laurel Lane | Italy  | 
...    | ...     | ...    | ...  | 

查看:

field   | value    | 
--------------|-------------------| 
name   | Al Wade Avery  | 
email   | [email protected] | 
address  | 1004 Court Street | 
country  | USA    | 
...   | ...    | 
name   | Antone Clay  | 
email   | [email protected] | 
address  | 6219 Devon Court | 
country  | UK    | 
...   | ...    | 
name   | Issac Luigi  | 
email   | [email protected] | 
address  | 43 Bridge Street | 
country  | USA    | 
...   | ...    | 
+2

你不想這樣做。你沒有將相似結果組合在一起的「id」。 –

回答

1

一個簡單的方法來做到這一點是使用union all

create view v_table as 
    select 'name' as field, name as value from t 
    union all 
    select 'email', email 
    union all 
    select 'address', address 
    union all 
    select 'country', country; 

但是,真的不想這樣做,因爲你正在失去有關哪些字段與原始數據中的哪一行相關的信息。如果你有一個id字段,你應該包括在視圖:

create view v_table as 
    select id, 'name' as field, name as value from t 
    union all 
    select id, 'email', email 
    union all 
    select id, 'address', address 
    union all 
    select id, 'country', country; 

否則,另一種獨特的列 - 或許name - 應包括在內。

+0

嗨戈登,感謝您的快速回復!您的代碼正在顯示: – tuliomarchetto

+0

彼此之下的所有'姓名',而不是所有'彼此之下的電子郵件'等。而不是保留訂單:'姓名','電子郵件','地址','國家'。 – tuliomarchetto

+0

@tuliomarchetto。 。 。 SQL表和結果集表示*無序*集,除非你有'order by'。在第二個版本中,您可以添加''by'id'來保持相似的行。 –