将sql表与多个相似的行MYSQL合并

时间:2011-07-03 00:37:40

标签: mysql sql database merge

我有以下MySQL表:

col1      col2        col3       col4       col5
A         abc         val2       NULL       NULL
A         abc         NULL       val3       val4
B         def         value2     NULL       value3
B         def         NULL       value4     NULL

我希望输出为

col1      col2        col3       col4       col5
A         abc         val2       val3       val4
B         def         value2     value4     value3

查询应该是什么?

1 个答案:

答案 0 :(得分:1)

您应该使用group by:

mysql> create table t3 (col1 varchar(16), col2 varchar(16), col3 varchar(16), col4 varchar(16), col5 varchar(16));
Query OK, 0 rows affected (0.08 sec)

mysql> insert into t3 (col1, col2, col3, col4, col5) values ('A', 'abc', 'val2', null, null), ('A', 'abc', null, 'val3', 'val4'), ('B', 'def', 'value2', null, 'value3'), ('B', 'def', null, 'value4', null);
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select col1, max(col2), max(col3), max(col4), max(col5) from t3 group by col1;
+------+-----------+-----------+-----------+-----------+
| col1 | max(col2) | max(col3) | max(col4) | max(col5) |
+------+-----------+-----------+-----------+-----------+
| A    | abc       | val2      | val3      | val4      |
| B    | def       | value2    | value4    | value3    |
+------+-----------+-----------+-----------+-----------+
2 rows in set (0.01 sec)