如何将具有相同ID的多行合并为一行?

时间:2022-05-05 18:12:58

How can I merge multiple rows with same ID into one row.

如何将具有相同ID的多行合并为一行。

I have table:

我有桌子:

+----+------+------+------+
| ID |  A   |  B   |  C   |
+----+------+------+------+
|  1 | 123  | 31   | 456  |
|  1 | 412  | NULL | 1    |
|  2 | 567  | 38   | 4    |
|  2 | 567  | NULL | NULL |
|  3 | 2    | NULL | NULL |
|  3 | 5    | NULL | NULL |
|  4 | 6    | 1    | NULL |
|  4 | 8    | NULL | 5    |
|  4 | NULL | NULL | 5    |
+----+------+------+------+

I want to have table : I have table:

我想要桌子:我有桌子:

+----+-----+------+------+-----+------+------+------+------+----+
| ID |  A  |  B   |  C   | A2  |  B2  |  C2  |  A3  |  B3  | C3 |
+----+-----+------+------+-----+------+------+------+------+----+
|  1 | 123 | 31   | 456  | 412 | NULL | 1    |      |      |    |
|  2 | 567 | 38   | 4    | 567 | NULL | NULL |      |      |    |
|  3 |   2 | NULL | NULL |   5 | NULL | NULL |      |      |    |
|  4 |   6 | 1    | NULL |   8 | NULL | 5    | NULL | NULL |  5 |
+----+-----+------+------+-----+------+------+------+------+----+

1 个解决方案

#1


0  

Try This:-

1 :- Please Change data table structure to disallow null value.

1: - 请更改数据表结构以禁用空值。

如何将具有相同ID的多行合并为一行?

  1. Query :-

    SELECT 
        GROUP_CONCAT(if (`A` ='0', 'NOVAL', `A`)SEPARATOR '----') as A,
        GROUP_CONCAT(if (`B` ='0', 'NOVAL', `B`)SEPARATOR '----') as B,
        GROUP_CONCAT(if (`C` ='0', 'NOVAL', `C`)SEPARATOR '----') as C 
    FROM que1
    GROUP BY id
    
  2. 查询: - 选择     GROUP_CONCAT(if(`A` ='0','NOVAL',`A`)SEPARATOR'----')为A,     GROUP_CONCAT(if(`B` ='0','NOVAL',`B`)SEPARATOR'----')为B,     GROUP_CONCAT(if(`C` ='0','NOVAL',`C`)SEPARATOR'----')为C 从que1 GROUP BY id

Now You can get the value using mysql_fetch_array

现在您可以使用mysql_fetch_array获取值

如何将具有相同ID的多行合并为一行?

#1


0  

Try This:-

1 :- Please Change data table structure to disallow null value.

1: - 请更改数据表结构以禁用空值。

如何将具有相同ID的多行合并为一行?

  1. Query :-

    SELECT 
        GROUP_CONCAT(if (`A` ='0', 'NOVAL', `A`)SEPARATOR '----') as A,
        GROUP_CONCAT(if (`B` ='0', 'NOVAL', `B`)SEPARATOR '----') as B,
        GROUP_CONCAT(if (`C` ='0', 'NOVAL', `C`)SEPARATOR '----') as C 
    FROM que1
    GROUP BY id
    
  2. 查询: - 选择     GROUP_CONCAT(if(`A` ='0','NOVAL',`A`)SEPARATOR'----')为A,     GROUP_CONCAT(if(`B` ='0','NOVAL',`B`)SEPARATOR'----')为B,     GROUP_CONCAT(if(`C` ='0','NOVAL',`C`)SEPARATOR'----')为C 从que1 GROUP BY id

Now You can get the value using mysql_fetch_array

现在您可以使用mysql_fetch_array获取值

如何将具有相同ID的多行合并为一行?