2011-07-03 66 views
-1

SQL表我有以下MySQL表:合併多個類似的行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

你應該用組:

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) 
+0

感謝我試圖做使用加入..有人拋出一個錯誤.. – Ankur