简体   繁体   English

如何合并MySQL记录

[英]How to combine MySQL records

I have a MySQL table that looks like this: 我有一个如下所示的MySQL表:

id |   id_item      | 
1  |   T0001        | 
2  |   T0002        |
2  |   T0003        |
3  |   T0004        |

and I want to change it like this: 我想这样更改它:

id |    id_item           | 
1  |   T0001,T0002        | 
2  |   T0001,T0003        |
2  |   T0001,T0004        |
3  |   T0002,T0003        |
4  |   T0002,T0004        |
5  |   T0003,T0004        |

and I want save in table item_2 like this: 我想这样保存在表item_2

    id |   id_item      | 
    1  |   T0001        | 
    2  |   T0002        |
    3  |   T0001        |
    4  |   T0003        |
    5  |   T0001        |
    6  |   T0004        |
    7  |   T0002        |
    8  |   T0003        |
    9  |   T0002        |
   10  |   T0004        |
   11  |   T0003        |
   12  |   T0004        |

Does anyone know how to do this by using PHP or MySQL? 有谁知道如何使用PHP或MySQL做到这一点?

You can generate this output via the following query: 您可以通过以下查询生成此输出:

SELECT
    CONCAT(t1.id_item, ',', t2.id_item) AS id_item
FROM yourTable t1
INNER JOIN yourTable t2
WHERE
    t2.id > t1.id
ORDER BY
    t1.id,
    t2.id

If you wanted to insert this data, you can use the above select to do an INSERT INTO ... SELECT into a new table. 如果要插入此数据,则可以使用上面的选择在新表中执行INSERT INTO ... SELECT I mention new table, because it probably would not make much sense to store CSV and non CSV data in the same column. 我提到了新表,因为将CSV和非CSV数据存储在同一列中可能没有多大意义。 Actually, I don't at all recommend storing CSV data in the first place. 实际上,我根本不建议首先存储CSV数据。 Instead, just generate it if you need it in your presentation layer using a query similar to what I have given above. 相反,如果您需要在表示层中使用类似于我上面给出的查询的查询来生成它,则只需生成它即可。

Demo here: 演示在这里:

Rextester Rextester

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM