如何创建 2 列 SQL 视图?
How create a 2 columns SQL View?
我需要创建一个 SQL 视图(使用 MySQL Workbench),它应该简单地获取一行的所有值并将它们与它们各自的列名称堆叠在第一个柱子。像这样:
原文Table:
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 |
... | ... |
一个简单的方法是使用 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
——。
我需要创建一个 SQL 视图(使用 MySQL Workbench),它应该简单地获取一行的所有值并将它们与它们各自的列名称堆叠在第一个柱子。像这样:
原文Table:
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 |
... | ... |
一个简单的方法是使用 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
——。