1

I must create migration to update question image attribute but i need to check some attributes from other tables, my schema looks like this:

question {
id,
name,
groupId,
imageUrl -> i need to update this
}

group {
id, 
name, 
quizId
}

quiz {
id,
name, 
type -> where type is 'History'
}

And i need to update attribute imageUrl from table question WHERE quiz type is for example 'History', i'm not sure how i can join this tables when using UPDATE. I tried something like this but it's not working like i want.

UPDATE question SET image_url = 'pathToImage' FROM quiz q WHERE q.type = 'History'
Sahbaz
  • 1,242
  • 4
  • 17
  • 39

3 Answers3

1

So this is best solution that i came up with, and it worked perfectly for my migration.

UPDATE question SET image_url = 'https://path_to_image.com' WHERE id IN (SELECT q.id FROM question q
            JOIN group AS g ON q.groupi_id = g.id
            JOIN quiz AS qu ON qu.id = g.quiz_id
            WHERE qu.type = 'Lifestyle')

So basically i update image_url to all questions with ID's in sub query, and this is easiest way to do this.

Sahbaz
  • 1,242
  • 4
  • 17
  • 39
0

JOIN three tables on this way:

UPDATE question q 
SET    image_url = 'pathToImage'
FROM   (select g.Id 
        from group g
        JOIN   quiz z
        ON     g.quizID = z.Id
        WHERE  z.type = 'History') p
ON     q.groupId = p.Id;
McNets
  • 10,352
  • 3
  • 32
  • 61
  • I actually already have links to images, so i need to set that link, im not sure how and where i set image url with your example ? – Sahbaz Mar 29 '17 at 20:36
  • With your example im getting syntax error at or near "ON" (last ON where you say q.groupId = z.Id – Sahbaz Mar 29 '17 at 20:53
  • I cannot see pathToImage field on none of your tables. – McNets Mar 29 '17 at 21:02
  • Path to image is actually link that i want to set, its not attrbute its actually value for image_url – Sahbaz Mar 29 '17 at 21:04
0

try:

   with cte as (
      select q.id qid
      from question q
      join "group" g on g.id = groupId
      join quiz z on z.id = quizId
      where type = 'History'
    )
    UPDATE question q
      SET image_url = 'pathToImage' 
    FROM cte.qid = q.id
Vao Tsun
  • 47,234
  • 13
  • 100
  • 132
  • no - I didn't check it. is there an error?.. please update question with DDL and DML to reproduce your env – Vao Tsun Mar 29 '17 at 20:56