如何获取表中子项的root的父ID

时间:2016-07-07 09:46:55

标签: mysql sql

这是我拥有的(表的名称是pobjects):

+----+------------+---------+-----------+------+---------+-----------+
| id | title      | user_id | published | uri  | type_id | parent_id |
+----+------------+---------+-----------+------+---------+-----------+
|  1 | file1.bpmn |       1 |         0 | NULL |       1 |      NULL |
|  2 | file2.bpmn |       1 |         0 | NULL |       1 |      NULL |
|  3 | file3.bpmn |       1 |         0 | NULL |       1 |      NULL |
|  4 | file4.bpmn |       2 |         0 | NULL |       1 |      NULL |
|  5 | root       |       1 |         0 | NULL |       2 |      NULL |
|  6 | root       |       2 |         0 | NULL |       2 |      NULL |
|  7 | root       |       3 |         0 | NULL |       2 |      NULL |
+----+------------+---------+-----------+------+---------+-----------+

这些行代表文件和根目录。我需要将每个文件的parent_id更新到同一用户的根目录id。所以,基本上我需要这个结果:

+----+------------+---------+-----------+------+---------+-----------+
| id | title      | user_id | published | uri  | type_id | parent_id |
+----+------------+---------+-----------+------+---------+-----------+
|  1 | file1.bpmn |       1 |         0 | NULL |       1 |         5 |
|  2 | file2.bpmn |       1 |         0 | NULL |       1 |         5 |
|  3 | file3.bpmn |       1 |         0 | NULL |       1 |         5 |
|  4 | file4.bpmn |       2 |         0 | NULL |       1 |         6 |
|  5 | root       |       1 |         0 | NULL |       2 |      NULL |
|  6 | root       |       2 |         0 | NULL |       2 |      NULL |
|  7 | root       |       3 |         0 | NULL |       2 |      NULL |
+----+------------+---------+-----------+------+---------+-----------+

由于我不是SQL大师,但我已经厌倦了不使用SQL的可能性,因此帮助将非常有用。

1 个答案:

答案 0 :(得分:4)

您可以使用UPDATE .. JOIN

执行此操作
UPDATE YourTable t
JOIN YourTable s
 ON(t.user_id = s.user_id and t.title <> 'root' and s.title = 'root')
SET t.parent_id = s.id