Reputation: 23
I have a MySQL table that looks like this:
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:
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?
Upvotes: 0
Views: 48
Reputation: 520958
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. I mention new table, because it probably would not make much sense to store CSV and non CSV data in the same column. Actually, I don't at all recommend storing CSV data in the first place. Instead, just generate it if you need it in your presentation layer using a query similar to what I have given above.
Demo here:
Upvotes: 1