MYSQL 使用嵌套子查询更新
MYSQL update with nested subquery
我有 3 个 table 这种格式:
Table Child:
id|parent_id|grandparent_id
1 1 null
2 2 null
3 3 null
Table Parent:
id|grandparent_id
1 1
2 1
3 2
Table盛大Parent:
id
1
2
我需要 运行 一个基于 Parent 中的 grandparent_id 更新 Child table 中的 grandparent_id 列的查询 table。所以 Child table 的正确最终形式是:
Table Child:
id|parent_id|grandparent_id
1 1 1
2 2 1
3 3 2
这是我目前的查询,但是 returns 超过 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
of Parent
with id = 2
is 1
!
请尝试以下查询:
Update child c,parent p
set c.grandparent_id = p.grandparent_id
where c.id = parent.id
and c.grandparent_id = ' '
我有 3 个 table 这种格式:
Table Child:
id|parent_id|grandparent_id
1 1 null
2 2 null
3 3 null
Table Parent:
id|grandparent_id
1 1
2 1
3 2
Table盛大Parent:
id
1
2
我需要 运行 一个基于 Parent 中的 grandparent_id 更新 Child table 中的 grandparent_id 列的查询 table。所以 Child table 的正确最终形式是: Table Child:
id|parent_id|grandparent_id
1 1 1
2 2 1
3 3 2
这是我目前的查询,但是 returns 超过 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
!
请尝试以下查询:
Update child c,parent p
set c.grandparent_id = p.grandparent_id
where c.id = parent.id
and c.grandparent_id = ' '