Reputation: 13302
Here is my current database schema:
category
table:
+------------+------------+
| id | name |
+------------+------------+
| 1 | category1 |
| 2 | category2 |
+------------+------------+
It is created in following way:
CREATE TABLE `category` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3889 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;
I need to create super category record for every existing category record in following way:
parent_id
(should reference to id
)parent_id
should be set to id
of its own record parent_id
should be set to id
of newly created record.Expected result:
+------------+------------+------------+
| id | name | parent_id |
+------------+------------+------------+
| 1 | category1 | 3 |
| 2 | category2 | 4 |
| 3 | category1 | 3 |
| 4 | category2 | 4 |
+------------+------------+------------+
The part I have difficulty with is setting parent_id
for existing records pointed to id
of new records.
Any ideas?
Upvotes: 0
Views: 35
Reputation: 2766
Need to do a self join:
update category p
inner join category c
on c.name=p.name
set c.parent_id=p.id
where c.id<>p.id
Upvotes: 1