【问题标题】:mysql Select values from multiple columns into single columnmysql 从多列中选择值到单列中
【发布时间】:2018-10-24 13:57:59
【问题描述】:

我在数据库中有一个表,它有几列包含相同类型的数据,这些值允许为空。我需要将每个 non-null 值选择到单个值列中,这些值关心它们所源自的行的 identity

所以,对于一个看起来像这样的表:

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

我希望将 aa、bb、cc 等的每个值选择到单个列中。我的结果数据应如下表所示。

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

我正在使用 mysql。在性能方面是否也有实现此目的的技术?

【问题讨论】:

  • 你不是说| 1 | eko | bb | 是预期输出中的第二行吗?
  • 谢谢,已编辑

标签: mysql database


【解决方案1】:

您可以只使用两个查询并使用两者的联合语句来附加两个集合:

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

但要使这个动态(任意数量的 v...),您必须遍历列。见:mysql, iterate through column names

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 2011-08-30
    • 1970-01-01
    • 2023-01-13
    • 2014-04-25
    相关资源
    最近更新 更多