将列合并到mySQL

时间:2015-11-26 02:49:06

标签: mysql sql

我在mySQL中将2列合并为单列时遇到问题。

这就是我想要发生的事情:

来自这个

+----------------+----------------+----------+
|    male        |     female     |   gender |
+----------------+----------------+----------+
|    male        |      null      |   null   |
+----------------+----------------+----------+
|    male        |      null      |   null   |
+----------------+----------------+----------+
|    null        |    female      |   null   |
+----------------+----------------+----------+
|    male        |      null      |   null   |
+----------------+----------------+----------+

到这个

+----------+
|   gender |
+----------+
|   male   |
+----------+
|   male   |
+----------+
|  female  |
+----------+
|   male   |
+----------+

我用过:

SELECT male, 
   female, 
   COALESCE(male, female) AS gender 
FROM nrco_ldap

但性别列中没有任何内容。

1 个答案:

答案 0 :(得分:3)

您正在尝试更新现有列,因此select显然不是这样做的方法。因此,您需要编写update查询,如下所示:

update nrco_ldap
set gender = coalesce(male,female)

如果除了填充gender列之外,您还要删除malefemale列,则需要编写相应的drop语句,如下所示:

alter table nrco_ldap drop column male;
alter table nrco_ldap drop column female;