简体   繁体   English

MySQL从多列选择值到单列

[英]mysql Select values from multiple columns into single column

I have a table in a database that has several columns containing the same sort of data, these values are allowed to be null . 我在数据库中有一个表,该表具有包含相同类型数据的几列,这些值允许为null I need to select each of the non-null values into a single column of values that care about the identity of the row from which they originated. 我需要将每个非空值都选择到单列的值中,这些值关心它们所源自的行的标识

So, for a table that looks like this: 因此,对于一个看起来像这样的表:

+---------+------+--------+------+
|   Id    | name  | v1    | v2   | 
+---------+------+--------+------+
|    1    | eko  | aa     |  bb  |
|    2    | agus | null   |  cc  |
|    3    | eko  | dd     |  null|
|    4    | budi | aa     |  null|
|    5    | siti | ff     |  gg  |
+---------+------+--------+------+

I wish to select each of the values aa,bb,cc, etc into a single column. 我希望将aa,bb,cc等每个值都选择到一个列中。 My result data should look like the following table. 我的结果数据应如下表所示。

+-------+-------+-------+
| id    | name  | v     |
+-------+-------+-------+
|  1    | eko   | aa    |
|  1    | eko   | bb    |
|  2    | agus  | cc    |
|  3    | eko   | dd    |
|  4    | budi  | aa    |
|  5    | siti  | ff    |
|  5    | siti  | gg    | 
+-------+-------+-------+

I am using mysql . 我正在使用mysql Is there a technique for achieving this with respect to performance too? 是否有一种在性能方面实现这一目标的技术?

You could just use two queries and use the union statement of the two to append the two sets: 您可以只使用两个查询,并使用两个查询的并集语句来追加两个集合:

Select id, v1 as v
From table 
where v1 is not null

union all

select id, v2 as v
from table
where v2 is not null

But to make this dynamic (any number of v...) you would have to iterate over the columns. 但是要使其动态(任意数量的v ...),您必须遍历各列。 See: mysql, iterate through column names 请参阅: mysql,遍历列名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM