我有 3 个这种格式的表:
表 child :
id|parent_id|grandparent_id
1 1 null
2 2 null
3 3 null
表父级:
id|grandparent_id
1 1
2 1
3 2
表祖 parent :
id
1
2
我需要运行一个查询,根据父表中的 grandparent_id 更新子表中的 grandparent_id 列。所以 Child 表的正确最终形式是: 表 child :
id|parent_id|grandparent_id
1 1 1
2 2 1
3 3 2
这是我目前的查询,但它返回超过 1 行,这是错误的:
update child set grandparent_id = (
select gpd.id from GrandParent gp, Parent p
where p.grandparent_id = gp.id)
where 1
最佳答案
您可以使用以下查询获取UPDATE
:
UPDATE Child SET Child.grandparent_id = (
SELECT GrandParent.id
FROM GrandParent INNER JOIN Parent ON GrandParent.id = Parent.grandparent_id
WHERE Parent.id = parent_id
) WHERE Child.grandparent_id IS NULL;
Demo: http://sqlfiddle.com/#!9/894e97/1/0 (modified table content to show the
UPDATE
is working).Hint: Your "correct" example is wrong:
GrandParent
ofParent
withid = 2
is1
!
关于MYSQL 更新嵌套子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43663979/