2

I have 3 tables in this format:

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 GrandParent:

id
1          
2          

I need to run a query that updates grandparent_id column in Child table based on the grandparent_id in Parent table. So the correct final form of Child table will be: Table Child:

id|parent_id|grandparent_id
1  1         1
2  2         1
3  3         2

This is the query I have at the moment but it returns more than 1 row which is wrong:

update child set grandparent_id = (
  select gpd.id from GrandParent gp, Parent p 
  where p.grandparent_id = gp.id) 
where 1

2 Answers 2

1

You can use the following query to get the 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!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked. So instead of normal join I had to Inner join? and why can't I just say where 1 to run it on everything even when it's not null?
If you want to UPDATE all Childs you don't need the WHERE part and you can remove it (no need for WHERE 1). I would choose the INNER JOIN to join the tables.
0

Please give a try on the below query:

Update child c,parent p
set c.grandparent_id = p.grandparent_id
where c.id = parent.id 
and c.grandparent_id = ' '

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.