我需要创建一个SQL视图(使用MySQL Workbench),它应该简单地获取一行的所有值,并将它们与第一列上的各自列名称堆叠起来。像这样:
原始表:
name | email | address | country | ...
------------------|----------------------|--------------------|------------|
Al Wade Avery | wade@hotmail.com | 1004 Court Street | USA |
Antone Clay | aclay@gmail.com | 6219 Devon Court | UK |
Issac Luigi | issac@hotmail.com | 43 Bridge Street | USA |
Lucio Andrea | lucioandrea@me.com | 2283 Laurel Lane | Italy |
... | ... | ... | ... |
查看:
field | value |
--------------|-------------------|
name | Al Wade Avery |
email | wade@hotmail.com |
address | 1004 Court Street |
country | USA |
... | ... |
name | Antone Clay |
email | aclay@gmail.com |
address | 6219 Devon Court |
country | UK |
... | ... |
name | Issac Luigi |
email | issac@hotmail.com |
address | 43 Bridge Street |
country | USA |
... | ... |
答案 0 :(得分: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
。