vendredi 27 février 2015

Determine parent id when moving hierarchical data to different tables?


I've got several tables which contain category and tag relationships for different posts. I'm trying to move the categories from the posts table into their respective tables while maintaining their relationships and hierarchical position. One of the steps in accomplishing this, is getting the parent id for each set of categories.


Here is the database schema:


enter image description here


Here is some sample data but I have omitted some columns for simplicity.


posts



+--------+------------+------------+------------+------------+
|post_id | category1 | category2 | category3 | category4 |
+--------+------------+------------+------------+------------+
| 1 | television | series | comedy | station |
+--------+------------+------------+------------+------------+
| 2 | television | reality | comedy | station |
+--------+------------+------------+------------+------------+


meta



+-------+-----------+
|meta_id| meta_name |
+-------+-----------+
| 1 |television |
+-------+-----------+
| 2 | series |
+-------+-----------+
| 3 | comedy |
+-------+-----------+
| 4 | station |
+-------+-----------+
| 5 | reality |
+-------+-----------+


Since both posts have a parent category of television, I need to somehow set all the sub-categories with that parent. Like this.


meta_data



+------------+------------+------------+
|meta_data_id| meta_id | parent |
+------------+------------+------------+
| 1 | 1 | 0 | <--is parent category, so stays 0
+------------+------------+------------+
| 2 | 2 | 1 |
+------------+------------+------------+
| 3 | 3 | 1 |
+------------+------------+------------+
| 4 | 4 | 1 |
+------------+------------+------------+
| 5 | 5 | 1 | ^--remaining categories should be 1
+------------+------------+------------+


I'm trying to build my query something like this...



UPDATE meta_data SET parent =
(SELECT posts.category1, posts.category2, posts.category3, posts.category4
FROM posts
LEFT JOIN meta ON meta.meta_name = websites.category1
LEFT JOIN meta_data ON meta.meta_id = meta_data.meta_id)
WHERE ...


If you could please just guide me on how to accomplish this I would really appreciate it.





Aucun commentaire:

Enregistrer un commentaire